<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">
            <template #goods>
              <el-select
                v-model="form.goods"
                filterable
                clearable
                remote
                reserve-keyword
                :remote-method="querySearch"
                placeholder="请选择商品名称"
                :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 #leader>
              <el-select v-model="form.leader" filterable clearable remote :remote-method="leadSearch" placeholder="请输入团长" style="width: 100%">
                <el-option v-for="item in userList" :key="item._id" :label="item.name" :value="item._id"> </el-option>
              </el-select>
            </template>
            <template #status>
              <el-option v-for="i in statusList" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </template>
            <template #group_config>
              <el-col :span="24" style="margin: 0 0 10px 0">
                <el-button type="primary" size="mini" @click="toReset()">重置</el-button>
              </el-col>
              <el-table :data="form.group_config" border size="mini">
                <el-table-column label="规格名称" prop="spec" align="center">
                  <template #default="{ row }">
                    <p>{{ row.spec.name }}</p>
                  </template>
                </el-table-column>
                <el-table-column label="团长价" prop="leader_price" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.leader_price" type="number" placeholder="请输入团长价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="团购价" prop="price" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.price" type="number" placeholder="请输入团购价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="团长提成金额" prop="leader_get" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.leader_get" type="number" placeholder="请输入团长提成金额"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="运费" prop="freight" align="center">
                  <template #default="{ row }">
                    <el-input v-model="row.freight" 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, 'group_config')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </data-form>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: group } = createNamespacedHelpers('group'); // 团表
const { mapActions: goodsConfig } = createNamespacedHelpers('goodsConfig'); // 团购-商品设置
const { mapActions: dictData } = createNamespacedHelpers('dictData'); // 字典
const { mapActions: goods } = createNamespacedHelpers('goods'); // 商品
const { mapActions: goodsSpec } = createNamespacedHelpers('goodsSpec'); // 商品规格
const { mapActions: users } = createNamespacedHelpers('users'); // 用户;
export default {
  name: 'detail',
  props: { id: { type: String } },
  components: {},
  data: function () {
    return {
      loadings: true,
      loading: false,
      // info部分
      infoFields: [
        { label: '商品名称', model: 'goods', custom: true },
        { label: '团长', model: 'leader', custom: true },
        { label: '人数限制', model: 'person_limit', type: 'number' },
        { label: '开始时间', model: 'start_time', type: 'datetime' },
        { label: '结束时间', model: 'end_time', type: 'datetime' },
        { label: '团状态', model: 'status', type: 'select' },
        { label: '团购设置', model: 'group_config', custom: true },
      ],
      rules: {
        goods: [{ required: true, message: '商品名称', trigger: 'change' }],
        leader: [{ required: false, message: '团长', trigger: 'change' }],
        person_limit: [{ required: true, message: '人数限制', trigger: 'blur' }],
        start_time: [{ required: true, message: '开始时间', trigger: 'change' }],
        end_time: [{ required: true, message: '结束时间', trigger: 'change' }],
        status: [{ required: true, message: '团状态', trigger: 'change' }],
      },
      form: {
        group_config: [], // 团购设置
      },
      // 商品列表
      goodsList: [],
      // 团状态
      statusList: [],
      // 团长
      userList: [],
      users: [],
    };
  },
  created() {
    this.searchOthers();
    this.search();
  },
  methods: {
    ...dictData({ getDict: 'query' }),
    ...goodsConfig({ goodsConfigQuery: 'query', goodsConfigFetch: 'fetch' }),
    ...group(['query', 'delete', 'fetch', 'update', 'create']),
    ...goods({ goodsQuery: 'query', goodsFetch: 'fetch' }),
    ...goodsSpec({ specQuery: 'query', specFetch: 'fetch' }),
    ...users({ userQuery: 'query' }),
    // 查询
    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);
          this.$set(this, `form`, res.data);
        }
      } else {
        const obj = { shop: _.get(this.user.shop, '_id') };
        this.$set(this, 'form', obj);
      }
      this.loadings = false;
    },
    // 查询团长
    leadSearch(value) {
      if (value) {
        let info = this.users.filter((f) => f.name.includes(value));
        this.$set(this, `userList`, info);
      } else this.$set(this, `userList`, this.users);
    },
    // 远程查询
    async querySearch(value) {
      this.loading = true;
      let res = await this.goodsQuery({ name: value });
      if (this.$checkRes(res)) {
        // let list = [];
        // for (const p1 of res.data) {
        //   let arr = await this.goodsConfigQuery({ goods: p1._id });
        //   if (this.$checkRes(arr)) if (arr.total > 0) list.push(p1);
        // }
        // this.$set(this, 'goodsList', list);
        this.$set(this, 'goodsList', res.data);
      }
      this.loading = false;
    },
    // 选择-查询商品
    async handleSelect(value) {
      let res = await this.goodsConfigQuery({ goods: value });
      if (this.$checkRes(res)) this.$set(this.form, 'group_config', res.data);
    },
    // 重置
    async toReset() {
      if (this.form.goods) {
        let res = await this.goodsConfigQuery({ goods: this.form.goods });
        if (this.$checkRes(res)) this.$set(this.form, 'group_config', res.data);
      } else this.$message({ type: `warning`, message: `请选择商品` });
    },
    // 删除
    toDel(index, type) {
      var list = this.form.group_config;
      list.splice(index, 1);
    },
    // 保存
    async toSave({ data }) {
      let res;
      if (this.form.group_config.length == 0) this.$message({ type: `warning`, message: `该商品没有规格设置团购金额，请在商品管理设置` });
      else {
        if (this.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;
      res = await this.getDict({ code: 'group_status' });
      if (this.$checkRes(res)) this.$set(this, `statusList`, res.data);
      // 团长列表
      res = await this.userQuery({ is_leader: '0' });
      if (this.$checkRes(res)) {
        for (const p1 of res.data) {
          p1.name = '团长' + '---' + p1.phone + '---' + p1.name;
        }
        this.$set(this, `userList`, res.data);
        this.$set(this, `users`, 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>
