<template>
  <div id="detail">
    <el-row>
      <el-col :span="24" class="main" v-loading="loadings" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
        <el-col :span="24" style="margin: 0 0 10px 0">
          <el-col :span="2"><el-button type="primary" size="mini" @click="toBack()">返回</el-button></el-col>
        </el-col>
        <el-col :span="24">
          <data-form :fields="infoFields" :rules="rules" v-model="form" labelWidth="150px" @save="toSave" @dataChange="dataChange">
            <template #is_use>
              <el-option v-for="i in is_useList" :key="i.model" :label="i.label" :value="i.value"></el-option>
            </template>
            <template #set>
              <el-col :span="24" style="margin: 0 0 10px 0">
                <el-button type="primary" size="mini" @click="toAdd()">添加规格商品</el-button>
              </el-col>
              <el-table :data="form.set" border size="mini">
                <el-table-column label="商品名称" prop="goods_name" align="center">
                  <template #default="{ row }">
                    <p>{{ row.goods_name }}</p>
                  </template>
                </el-table-column>
                <el-table-column label="规格名称" prop="spec_name" align="center">
                  <template #default="{ row }">
                    <p>{{ row.spec_name }}</p>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="set_num" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.set_num" type="number" placeholder="请输入组合套装数量"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单价" prop="set_money" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.set_money" type="number" placeholder="请输入套装销售金额"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button type="danger" size="mini" @click="toDel(scope.$index, 'set')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-col :span="24" style="margin: 10px 0 0 0; text-align: center">
                <el-button type="warning" size="mini" @click="toMoney()">计算套装金额</el-button>
              </el-col>
            </template>
            <template #stock v-if="form.single_stock == '0'">
              <el-input v-model="form.stock" type="number" placeholder="请输入库存数量"></el-input>
            </template>
          </data-form>
        </el-col>
      </el-col>
    </el-row>
    <e-dialog :dialog="dialog" @toClose="toClose">
      <template v-slot:info>
        <data-form :fields="diaFields" :rules="diaRules" v-model="diaForm" labelWidth="150px" @save="onSubmit" @dataChange="diaChange">
          <template #goods>
            <el-select
              v-model="diaForm.goods"
              filterable
              clearable
              remote
              reserve-keyword
              :remote-method="goodsSearch"
              placeholder="请输入商品名称，便于查询"
              :loading="loading"
              @change="goodsSelect"
              style="width: 100%"
            >
              <el-option v-for="item in goodsList" :key="item._id" :label="item.name" :value="item._id"> </el-option>
            </el-select>
          </template>
          <template #spec>
            <el-option v-for="item in specList" :key="item._id" :label="item.name" :value="item._id"> </el-option>
          </template>
        </data-form>
      </template>
    </e-dialog>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
import * as util from '@/util/computed';
const _ = require('lodash');
const { mapActions: goodsSet } = createNamespacedHelpers('goodsSet');
const { mapActions: goods } = createNamespacedHelpers('goods');
const { mapActions: goodsSpec } = createNamespacedHelpers('goodsSpec');
const { mapActions: dictData } = createNamespacedHelpers('dictData');

export default {
  name: 'detail',
  props: { id: { type: String } },
  components: {},
  data: function () {
    return {
      loadings: true,
      // form
      infoFields: [
        { label: '套装名称', model: 'name' },
        { label: '是否使用', model: 'is_use', type: 'select' },
        { label: '商品规格组合', model: 'set', custom: true },
        { label: '套装销售金额', model: 'sell_money', type: 'number' },
        { label: '运费', model: 'freight', type: 'number' },
      ],
      rules: {
        name: [{ required: true, message: '套装名称', trigger: 'blur' }],
        is_use: [{ required: true, message: '是否使用', trigger: 'change' }],
        sell_money: [{ required: true, message: '套装销售金额', trigger: 'blur' }],
        freight: [{ required: true, message: '运费', trigger: 'blur' }],
      },
      form: {
        set: [],
      },
      // 是否使用
      is_useList: [],
      // 弹框
      dialog: { title: '信息管理', show: false, type: '1' },
      diaFields: [
        { label: '商品名称', model: 'goods', custom: true },
        { label: '规格名称', model: 'spec', type: 'select' },
        { label: '数量', model: 'set_num', type: 'number' },
        { label: '单价', model: 'set_money', type: 'number' },
      ],
      diaRules: {
        goods: [{ required: true, message: '商品名称', trigger: 'change' }],
        spec: [{ required: true, message: '规格名称', trigger: 'blur' }],
        set_num: [{ required: true, message: '数量', trigger: 'blur' }],
        set_money: [{ required: true, message: '单价', trigger: 'blur' }],
      },
      diaForm: {},
      list: [],
      loading: false,
      goodsList: [],
      specList: [],
    };
  },
  created() {
    this.searchOthers();
    this.search();
  },
  methods: {
    ...dictData({ getDict: 'query' }),
    ...goods({ goodsQuery: 'query', goodsFetch: 'fetch' }),
    ...goodsSpec({ specQuery: 'query', specFetch: 'fetch' }),
    ...goodsSet(['query', 'delete', 'fetch', 'update', 'create']),

    // 查询
    async search() {
      if (this.id) {
        const res = await this.fetch(this.id);
        if (this.$checkRes(res)) this.$set(this, `form`, res.data);
      } else {
        const obj = { is_use: '0', set: [], freight: 0, shop: this.user.shop._id };
        this.$set(this, 'form', obj);
      }
      this.loadings = false;
    },
    toAdd() {
      this.dialog = { title: '信息管理', show: true, type: '1' };
    },
    // 远程查询店铺
    async goodsSearch(value) {
      this.loading = true;
      let res = await this.goodsQuery({ shop: this.user.shop._id, name: value });
      if (this.$checkRes(res)) this.$set(this, 'goodsList', res.data);
      this.loading = false;
    },
    // 选择-查询商品
    async goodsSelect(value) {
      let res = await this.specQuery({ goods: value });
      if (this.$checkRes(res)) this.$set(this, 'specList', res.data);
      res = await this.goodsFetch(value);
      if (this.$checkRes(res)) this.$set(this.diaForm, 'goods_name', res.data.name);
    },
    async diaChange({ model, value }) {
      if (model == 'spec') {
        let res = await this.specFetch(value);
        if (this.$checkRes(res)) {
          this.$set(this.diaForm, 'spec_name', res.data.name);
          this.$set(this.diaForm, 'set_money', res.data.sell_money);
        }
      }
    },
    onSubmit({ data }) {
      if (this.form.set.length == 0) {
        let list = [];
        list.push(data);
        this.$set(this.form, 'set', list);
      } else {
        this.form.set.push(data);
      }
      this.toClose();
    },
    // 关闭
    toClose() {
      this.diaForm = {};
      this.dialog = { title: '信息管理', show: false, type: '1' };
    },
    // 删除
    toDel(index, type) {
      var list = this.form.set;
      list.splice(index, 1);
    },
    // 计算金额
    toMoney() {
      let money = 0;
      for (const p1 of this.form.set) {
        let num = util.multiply(p1.set_num, p1.set_money);
        money = util.plus(money, num);
      }
      this.$set(this.form, 'sell_money', money);
    },
    dataChange({ model, value }) {},
    // 保存
    async toSave({ data }) {
      if (data.set.length > 0) {
        let res;
        if (data._id) res = await this.update(data);
        else res = await this.create(data);
        if (this.$checkRes(res)) {
          this.$message({ type: `success`, message: `维护信息成功` });
          this.toBack();
        }
      } else {
        this.$message({ type: `warning`, message: `还未添加套装商品，不可保存` });
      }
    },
    // 返回
    toBack() {
      this.$emit('toBack');
    },
    // 查询其他信息
    async searchOthers() {
      // 是否使用
      let res = await this.getDict({ code: 'use' });
      if (this.$checkRes(res)) this.$set(this, 'is_useList', res.data);
    },
  },
  computed: {
    ...mapState(['user']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped></style>
