<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 #goods>
              <el-select
                v-model="form.goods"
                filterable
                remote
                reserve-keyword
                placeholder="请选择商品名称"
                :remote-method="querySearch"
                :loading="loading"
                @change="handleSelect"
                style="width: 100%"
              >
                <el-option v-for="item in goodsList" :key="item._id" :label="item.name" :value="item._id"> </el-option>
              </el-select>
              <p style="color: red">输入商品名称查询</p>
            </template>
            <template #spec>
              <el-option v-for="item in specList" :key="item._id" :label="item.name" :value="item._id"> </el-option>
            </template>
            <template #buy_limit>
              <el-option v-for="i in buy_limitList" :key="i.model" :label="i.label" :value="i.value"></el-option>
            </template>
          </data-form>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
import * as util from '@/util/computed';
const { mapActions: goodsConfig } = createNamespacedHelpers('goodsConfig');
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,
      // info部分
      infoFields: [
        { label: '商品名称', model: 'goods', custom: true },
        { label: '商品规格', model: 'spec', type: 'select' },
        { label: '团长价', model: 'leader_price', type: 'text' },
        { label: '团购价', model: 'price', type: 'number' },
        { label: '团长提成金额', model: 'leader_get', type: 'number' },
        { label: '运费', model: 'freight', type: 'number' },
        { label: '购买限制', model: 'buy_limit', type: 'select' },
        { label: '购买数量界限', model: 'limit_num', type: 'number' },
      ],
      rules: {
        goods: [{ required: true, message: '商品名称', trigger: 'change' }],
        spec: [{ required: true, message: '商品规格', trigger: 'change' }],
        price: [{ required: true, message: '团购价', trigger: 'blur' }],
        leader_get: [{ required: true, message: '团长提成金额', trigger: 'blur' }],
        freight: [{ required: true, message: '运费', trigger: 'blur' }],
      },
      form: {},
      // 加载
      loading: false,
      // 远程搜索商品列表
      goodsList: [],
      // 规格列表
      specList: [],
      // 购买限制
      buy_limitList: [],
      // 团长价
      leader_price: '',
    };
  },
  created() {
    this.searchOthers();
    this.search();
  },
  methods: {
    ...dictData({ getDict: 'query' }),
    ...goods({ goodsQuery: 'query', goodsFetch: 'fetch' }),
    ...goodsSpec({ specQuery: 'query', specFetch: 'fetch' }),
    ...goodsConfig(['query', 'delete', 'fetch', 'update', 'create']),
    // 查询
    async search() {
      if (this.id) {
        const res = await this.fetch(this.id);
        if (this.$checkRes(res)) {
          // 商品
          let arr = await this.goodsFetch(res.data.goods);
          if (this.$checkRes(arr)) this.goodsList.push(arr.data);
          // 规格
          let aee = await this.specFetch(res.data.spec);
          if (this.$checkRes(aee)) {
            this.specList.push(aee.data);
            if (!_.get(res, 'data.leader_price')) {
              res.data.leader_price = _.get(aee, 'data.leader_price', _.get(aee, 'data.sell_money'));
            }
          }
          this.$set(this, `form`, res.data);
        }
      } else {
        const obj = { shop: _.get(this.user.shop, '_id') };
        this.$set(this, 'form', obj);
      }
      this.loadings = false;
    },
    // 远程查询
    async querySearch(value) {
      this.loading = true;
      let res = await this.goodsQuery({ name: value });
      if (this.$checkRes(res)) this.$set(this, 'goodsList', res.data);
      this.loading = false;
    },
    // 选择-查询规格
    async handleSelect(value) {
      let res = await this.specQuery({ goods: value });
      if (this.$checkRes(res)) this.$set(this, 'specList', res.data);
    },
    dataChange({ model, value }) {
      if (model == 'spec') {
        let info = this.specList.find((f) => f._id == value);
        if (info) this.$set(this.form, 'freight', info.freight);
        if (info && info.leader_price) this.$set(this, 'leader_price', info.leader_price);
        if (info && !info.leader_price) this.$set(this, 'leader_price', '');
        if (info && info.buy_limit) this.$set(this.form, 'buy_limit', info.buy_limit);
        if (info && info.limit_num) this.$set(this.form, 'limit_num', info.limit_num);
      }
      if (model === 'price') {
        const spec = this.specList.find((f) => f._id === this.form.spec);
        if (!spec) return;
        const leader_price = _.get(spec, 'leader_price');
        let price = util.minus(this.form.price, leader_price);
        if (price > 0) this.$set(this.form, 'leader_get', price);
        else this.$set(this.form, 'leader_get', 0);
      }
    },
    // 保存
    async toSave({ data }) {
      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();
      }
    },
    // 返回
    toBack() {
      this.$emit('toBack');
    },
    // 查询其他信息
    async searchOthers() {
      // 购买限制
      let res = await this.getDict({ code: 'buy_limit' });
      if (this.$checkRes(res)) this.$set(this, 'buy_limitList', 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>
