<template>
  <div>
    <el-dialog :title="title" v-if="open" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="会员信息">
          <el-table border style="margin-top:5px;" v-loading="userloading" :data="users">
            <el-table-column label="ID" align="center" prop="userId" />
            <el-table-column label="会员头像" align="center" width="80">
              <template slot-scope="scope">
                <el-popover placement="right" title="" trigger="hover">
                  <img slot="reference" :src="scope.row.avatar" width="50">
                  <img :src="scope.row.avatar" style="max-width: 120px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="昵称" align="center" prop="nickName" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in userStatusOptions"
                  v-if="scope.row.status == item.dictValue"
                  :key="index"
                >{{ item.dictLabel }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="收货信息" prop="addressId">
          <el-row>
            <el-col>
              <el-button plain type="primary" icon="el-icon-plus" @click="handleAddUserAddress">添加收货地址</el-button>
            </el-col>
          </el-row>
          <el-radio-group v-model="form.addressId" style="width:100%">
            <el-table border style="margin-top:5px;" v-loading="addressloading" :data="address">
              <el-table-column label="ID" align="center">
                <template slot-scope="scope">
                  <el-radio :label="scope.row.addressId"></el-radio>
                </template>
              </el-table-column>
              <el-table-column label="收货人姓名" align="center" prop="realName" />
              <el-table-column label="收货人电话" align="center" prop="phone" />
              <el-table-column label="地址" align="center" prop="detail">
                <template slot-scope="scope">
                  {{ scope.row.province }} {{ scope.row.city }} {{ scope.row.district }} {{ scope.row.detail }}
                </template>
              </el-table-column>
            </el-table>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品列表">
          <el-row>
            <el-col>
              <el-button plain type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
            </el-col>
          </el-row>
          <el-table border :key="tablekey" width="100%" style="margin-top:5px;" :data="products">
            <el-table-column label="商品编号" align="center" prop="barCode" />
            <el-table-column label="商品图片" align="center" width="100">
              <template slot-scope="scope">
                <el-popover placement="right" title="" trigger="hover">
                  <img slot="reference" :src="scope.row.image" width="50">
                  <img :src="scope.row.image" style="max-width: 50px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
            <el-table-column label="商品规格" align="center" prop="sku" />
            <el-table-column label="库存" align="center" prop="stock" />
            <el-table-column label="单价" align="center" prop="price" />
            <el-table-column label="数量" align="center" prop="count" width="200px" :key="tablekey">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.count"
                    @change="handleProductCountChange(scope.row)"
                    size="mini"
                    :min="1"
                    :max="scope.row.stock"
                  ></el-input-number>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="小计" align="center" prop="money" />
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col>
              <span>商品合计:{{ products.length }}</span>
              <span style="margin-left:10px;">商品总价:{{ totalMoney.toFixed(2) }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择支付方式" clearable size="small">
            <el-option
              v-for="item in payTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="改价" prop="payPrice" v-if="projectCode !== 'ddgy'">
          <el-input-number v-model="form.payPrice" placeholder="修改商品总价" size="medium" :precision="2" :min="0.01" :step="0.1" />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice" v-if="projectCode === 'ddgy'">
          <el-input-number v-model="form.totalPrice" placeholder="修改商品总价" size="medium" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="定金" prop="payPrice" v-if="projectCode === 'ddgy'">
          <el-input-number v-model="form.payPrice" @change="syncAmountByTotalPriceAndDeposit" placeholder="修改实际支付金额" size="medium" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="物流代收" prop="amount" v-if="form.payType == '3' && projectCode !== 'ddgy'">
          <el-input-number v-model="form.amount" placeholder="平台支付价格" size="medium" :precision="2" :min="0.01" :step="0.1" />
        </el-form-item>
        <el-form-item label="代收货款" prop="amount" v-if="form.payType == '3' && projectCode === 'ddgy'">
          <el-input-number v-model="form.amount" placeholder="代收货款价格" size="medium" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="订单备注" prop="mark">
          <el-input type="textarea" rows="2" v-model="form.mark" placeholder="" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="product.title" v-if="product.open" :visible.sync="product.open" width="1000px" append-to-body>
      <product-select @selectProduct="selectProduct" />
    </el-dialog>
    <el-dialog :title="userAddress.title" v-if="userAddress.open" :visible.sync="userAddress.open" width="800px" append-to-body>
      <add-user-address ref="addUserAddress" @addUserAddress="onAddUserAddress" />
    </el-dialog>
  </div>
</template>

<script>
import { createUserOrder } from '@/api/hisStore/storeOrder';
import { userList } from '@/api/store/user';
import { getAddressList } from '@/api/users/userAddress';
import productSelect from '@/views/hisStore/components/productSelect';
import addUserAddress from '@/views/hisStore/components/addUserAddress';

export default {
  name: 'CreateOder',
  components: { productSelect, addUserAddress },
  data() {
    return {
      open: false,
      title: '创建订单',
      projectCode: process.env.VUE_APP_PROJECT_CODE,
      form: {
        addressId: null,
        userId: null,
        products: [],
        payType: null,
        totalPrice: undefined,
        payPrice: undefined,
        amount: undefined,
        mark: null,
      },
      rules: {
        addressId: [{ required: true, message: '收货信息不能为空' }],
        payType: [{ required: true, message: '支付方式不能为空' }],
      },
      users: [],
      userloading: false,
      userStatusOptions: [],
      address: [],
      addressloading: false,
      products: [],
      product: {
        open: false,
        title: '商品选择',
      },
      userAddress: {
        open: false,
        title: '创建收货地址',
      },
      tablekey: false,
      totalMoney: 0,
      payTypeOptions: [],
    };
  },
  watch: {
    "form.payPrice"() {
      this.syncAmountByTotalPriceAndDeposit();
    },
    "form.totalPrice"() {
      this.syncAmountByTotalPriceAndDeposit();
    },
  },
  created() {
    this.getDicts('store_pay_type').then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts('user_status').then(response => {
      this.userStatusOptions = response.data;
    });
  },
  methods: {
    /** 由父组件调用，row 需包含 fsUserId */
    show(row) {
      if (!row || !row.fsUserId) {
        return;
      }
      this.reset();
      this.open = true;
      this.title = '创建订单';
      this.form.userId = row.fsUserId;
      this.loadUserList(row.fsUserId);
    },
    reset() {
      this.form = {
        addressId: null,
        userId: null,
        products: [],
        payType: null,
        totalPrice: undefined,
        payPrice: undefined,
        amount: undefined,
        mark: null,
      };
      this.users = [];
      this.address = [];
      this.products = [];
      this.totalMoney = 0;
      if (this.$refs.form) {
        this.resetForm('form');
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    loadUserList(userId) {
      this.userloading = true;
      this.users = [];
      this.address = [];
      userList({ userId: userId }).then(response => {
        const list = response.rows || response.data || [];
        this.users = Array.isArray(list) ? list : [list];
        this.userloading = false;
        if (this.users.length > 0) {
          this.form.userId = this.users[0].userId || userId;
          this.getAddressList(this.form.userId);
        }
      }).catch(() => {
        this.userloading = false;
      });
    },
    getAddressList(userId) {
      const data = { userId: userId };
      this.addressloading = true;
      this.address = [];
      getAddressList(data).then(response => {
        this.address = response.data || response.rows || [];
        this.addressloading = false;
      }).catch(() => {
        this.addressloading = false;
      });
    },
    handleAddUserAddress() {
      if (this.form.userId == null) {
        this.msgError('请选择会员');
        return;
      }
      this.userAddress.open = true;
      setTimeout(() => {
        this.$refs.addUserAddress.init(this.form.userId);
      }, 500);
    },
    onAddUserAddress() {
      this.userAddress.open = false;
      this.getAddressList(this.form.userId);
    },
    handleAddProduct() {
      this.product.open = true;
    },
    compute() {
      this.totalMoney = 0;
      const that = this;
      this.products.forEach(function(value) {
        that.totalMoney += value.money;
      });
    },
    handleProductCountChange(row) {
      this.tablekey = !this.tablekey;
      row.money = row.count * row.price;
      this.$forceUpdate();
      this.compute();
    },
    selectProduct(row) {
      for (let i = 0; i < this.products.length; i++) {
        if (this.products[i].id == row.id) {
          return;
        }
      }
      row.count = 1;
      row.money = row.count * row.price;
      this.products.push(row);
      this.$message.success('商品' + row.productName + '添加成功');
      this.compute();
    },
    handleDeleteProduct(row) {
      this.products.splice(this.products.findIndex(item => item.id === row.id), 1);
      this.compute();
    },
    syncAmountByTotalPriceAndDeposit() {
      if (this.projectCode !== 'ddgy') {
        return;
      }
      if (this.form.totalPrice === null || this.form.totalPrice === undefined) {
        return;
      }
      if (this.form.payPrice === null || this.form.payPrice === undefined) {
        return;
      }
      const amount = Number((this.form.totalPrice - this.form.payPrice).toFixed(2));
      this.$set(this.form, 'amount', amount > 0 ? amount : null);
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (this.products.length === 0) {
          this.msgError('请选择商品');
          return;
        }
        if (!this.form.userId) {
          this.msgError('会员信息不能为空');
          return;
        }
        this.form.products = this.products;
        if (valid) {
          createUserOrder(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess('创建成功');
              this.open = false;
              this.reset();
              this.$emit('success');
            }
          });
        }
      });
    },
  },
};
</script>
