<template>
  <div id="spec">
    <template v-if="view === 'list'">
      <el-row>
        <el-col :span="24" class="btn">
          <el-col :span="2">
            <el-button size="mini" type="primary" @click="toBack()">返回</el-button>
          </el-col>
          <el-col :span="20">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item v-for="(item, index) in data" :key="index">{{ item.name }}</el-breadcrumb-item>
            </el-breadcrumb>
          </el-col>
        </el-col>
      </el-row>
      <el-col :span="24" class="one"> <span>规格管理</span> </el-col>

      <data-search :fields="searchFields" v-model="searchInfo" @query="search">
        <template #status>
          <el-option v-for="i in statusList" :key="i.model" :label="i.label" :value="i.value"></el-option>
        </template>
      </data-search>
      <data-btn :fields="btnFields" @add="toAdd" />
      <data-table ref="dataTable" :fields="fields" :opera="opera" :data="list" :total="total" @edit="toEdit" @delete="toDelete" @query="search" @copy="toCopy">
        <template #code="{ row, item }">
          <el-link type="primary" @click="toData(row)">{{ row[item.model] }}</el-link>
        </template>
      </data-table>
    </template>
    <template v-else>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" size="mini" @click="toBackList()">返回</el-button>
        </el-col>
        <el-col :span="24">
          <data-form :span="12" :fields="infoFields" :rules="rules" v-model="form" labelWidth="150px" @save="toSave">
            <template #status>
              <el-option v-for="i in statusList" :key="i.model" :label="i.label" :value="i.value"></el-option>
            </template>
            <template #can_group>
              <el-option v-for="i in tfList" :key="i.model" :label="i.label" :value="i.value"></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-row>
    </template>
  </div>
</template>

<script>
// 找到该商品下的规格定义
const _ = require('lodash');
import methodUtil from '@/util/opera';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('goodsSpec');
const { mapActions: dictData } = createNamespacedHelpers('dictData');
const { mapActions: goods } = createNamespacedHelpers('goods');

export default {
  name: 'spec',
  props: {},
  components: {},
  data: function () {
    return {
      view: 'list',
      fields: [
        { label: '规格名称', model: 'name', showTip: false },
        { label: '库存', model: 'num' },
        { label: '实际销售价格', model: 'sell_money' },
        { label: '划掉销售价格', model: 'flow_money' },
        {
          label: '购买限制',
          model: 'buy_limit',
          format: (i) => {
            let data = this.buy_limitList.find((f) => f.value == i);
            if (data) return data.label;
            else return '暂无';
          },
        },
        { label: '限制数量界限', model: 'limit_num' },
        { label: '运费', model: 'freight' },
        { label: '团长价格', model: 'leader_price' },
        { label: '状态', model: 'status', format: (i) => (i === '0' ? '使用中' : '已禁用') },
        { label: '排序', model: 'sort' },
      ],
      opera: [
        { label: '修改', method: 'edit' },
        { label: '复制', method: 'copy' },
        { label: '删除', method: 'delete', confirm: true, type: 'danger' },
      ],
      list: [],
      total: 0,
      limit: 10,
      btnFields: [{ label: '添加', method: 'add' }],
      defaultSearch: {},
      searchInfo: {},
      searchFields: [
        { label: '规格名称', model: 'name' },
        { label: '状态', model: 'status', type: 'select' },
      ],
      infoFields: [
        { label: '规格名称', model: 'name' },
        { label: '库存', model: 'num', type: 'number' },
        { label: '实际销售价格', model: 'sell_money', type: 'number' },
        { label: '划掉销售价格', model: 'flow_money', type: 'number' },
        { label: '购买限制', model: 'buy_limit', type: 'select' },
        { label: '限制数量界限', model: 'limit_num', type: 'number' },
        { label: '排序', model: 'sort', type: 'number' },
        { label: '运费', model: 'freight', type: 'number' },
        { label: '状态', model: 'status', type: 'select' },
        { label: '团长价格', model: 'leader_price', type: 'number' },
        { label: '图片', model: 'file', type: 'upload', url: '/files/point/goodsSpec/upload' },
      ],
      rules: {
        freight: [{ required: true, message: '请输入运费', trigger: 'blur' }],
      },
      form: {},

      statusList: [],
      // 是否可以团购
      tfList: [],
      data: [],
      // 购买限制
      buy_limitList: [],
    };
  },
  computed: {
    ...mapState(['user']),
    goods() {
      return this.$route.params.id;
    },
  },
  created() {
    this.defaultSearch.goods = this.goods;
    this.searchOthers();
    this.search();
    this.toData();
  },
  methods: {
    ...dictData({ getDict: 'query' }),
    ...mapActions(['query', 'fetch', 'update', 'delete', 'create']),
    ...goods({ goodsFetch: 'fetch' }),
    ...methodUtil,
    // 添加自定义
    initAddData() {
      const obj = { goods: this.goods, status: '0', freight: 0, buy_limit: '0' };
      this.$set(this, 'form', obj);
    },
    async toData(row) {
      let data = this.data;
      let res = await this.goodsFetch(this.goods);
      if (this.$checkRes(res)) data.push(res.data);
      this.search();
    },
    // 复制
    async toCopy({ data }) {
      this.$confirm('是否确认复制该商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        data.name = data.name + '-复制';
        delete data.id;
        delete data._id;
        delete data.meta;
        delete data.__v;
        let res;
        res = await this.create(data);
        if (this.$checkRes(res)) {
          this.$message({ type: `success`, message: `复制成功` });
          this.search();
          this.toBackList();
        }
      });
    },
    // 保存
    async toSave({ data }) {
      let res;
      if (!data.leader_price) data.leader_price = data.sell_money;
      if (data.id) res = await this.update(data);
      else res = await this.create(data);
      if (this.$checkRes(res)) {
        this.$message({ type: `success`, message: `维护信息成功` });
        this.search();
        this.toBackList();
      }
    },
    // 修改
    async toEdit({ data }) {
      const res = await this.fetch(data._id);
      if (this.$checkRes(res)) {
        this.$set(this, `form`, res.data);
        this.view = 'info';
      } else this.$message.error('未找到指定数据');
    },
    // 返回
    toBack() {
      this.data.pop();
      window.history.go('-1');
    },
    // 返回列表
    toBackList() {
      this.view = 'list';
      this.form = {};
    },
    // 查询其他信息
    async searchOthers() {
      // 状态
      let res = await this.getDict({ code: 'status' });
      if (this.$checkRes(res)) this.$set(this, 'statusList', res.data);
      // 是否可以团购
      res = await this.getDict({ code: 'tf' });
      if (this.$checkRes(res)) this.$set(this, 'tfList', res.data);
      // 购买限制
      res = await this.getDict({ code: 'buy_limit' });
      if (this.$checkRes(res)) this.$set(this, 'buy_limitList', res.data);
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped>
.btn {
  margin: 10px 10px 20px 10px;
  .el-breadcrumb {
    font-size: 16px;
    line-height: 30px;
  }
}
.one {
  margin: 0 0 10px 0;

  span:nth-child(1) {
    font-size: 20px;
    font-weight: 700;
    margin-right: 10px;
  }
}
.el-col {
  margin: 10px 0;
}
</style>
