<template>
  <el-dialog :title="title" width="1150px" class="dialog-width" :visible="dialogFormVisible" :modal-append-to-body="true"
    append-to-body :close-on-click-modal="false" @close="cancelForm">
    <section>
      <el-form ref="ruleForm" :model="formList" label-width="100px" :rules="rules">
        <el-form-item label="佣金计算" prop="isSub" v-if="params.productId">
          <el-radio-group v-model="formList.isSub" @input="inputradioGroup">
            <el-radio :label="0" v-if="pageType !== 'config'">默认佣金</el-radio>
            <el-radio :label="1">按比例</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品名称" v-if="productName" style="width: 270px;">
          <el-input v-model="productName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="最大比例" prop="maxBrokerage" style="width: 270px;">
          <el-input v-model.number="formList.maxBrokerage"> <template
              slot="append">%</template></el-input>
        </el-form-item>
        <el-form-item label="一级返佣" prop="retailStoreBrokerageFirstRatio"
          v-if="formList.isSub == null || formList.isSub == 1" style="width: 270px;">
          <el-input v-model.number="formList.retailStoreBrokerageFirstRatio"> <template
              slot="append">%</template></el-input>
        </el-form-item>
        <el-form-item label="二级返佣" prop="retailStoreBrokerageSecondRatio"
          v-if="formList.isSub == null || formList.isSub == 1" style="width: 270px;">
          <el-input v-model.number="formList.retailStoreBrokerageSecondRatio"> <template
              slot="append">%</template></el-input>
        </el-form-item>
        <el-tabs v-model="formList.activeName" type="card" @tab-click="handleClick"
          v-if="formList.isSub == null || formList.isSub == 1">
          <el-tab-pane label="渠道返佣" name="first">
            <Channelrebates ref='Channelref'></Channelrebates>
          </el-tab-pane>
          <el-tab-pane label="部门绩效" name="second">
            <Departmentperformance ref='Departref'></Departmentperformance>
          </el-tab-pane>
          <el-tab-pane label="部门成员绩效" name="third">
            <members ref='Membersref'></members>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </section>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelForm()">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Channelrebates from './Channelrebates'
import Departmentperformance from './Departmentperformance'
import members from './members'
import { brokerageConfigloadApi, brokerageConfigSaveApi } from '@/api/distribution';
export default {
  props: ['visible', 'params', "pageType", "productName"],
  components: {
    Channelrebates,
    Departmentperformance,
    members
  },

  data() {
    return {
      dialogFormVisible: this.visible,
      formList: {
        activeName: 'first',
        isSub: null
      },
      configChannelListArr: [],
      configDepartListArr: [],
      configMembersListArr: [],
      rules: {
        isSub: [{ required: true, message: '必填项', trigger: 'change' }],
      },
      title: '设置默认佣金'
    }
  },

  watch: {
    visible() {
      this.dialogFormVisible = this.visible
    }
  },

  mounted() {
    this.pageType === 'merchandise' ? this.title = '设置分佣' : null;
    this.brokerageConfigload()
  },

  methods: {
    brokerageConfigload() {
      if (this.params.productId.length > 1) {
        this.pageType === 'merchandise' ? this.formList.isSub = 1 : null;
        return;
      }

      let param = { ...this.params };
      if (this.params.productId.length === 1) {
        param.productId = this.params.productId[0];
      }

      brokerageConfigloadApi(param).then(res => {
        this.formList = res
        this.formList.activeName = 'first'
        this.pageType === "config" ? this.formList.isSub = 1 : null;
        if (res.configChannelList.length) {
          res.configChannelList.forEach((item, index) => {
            if (!item.index) {
              this.$set(item, 'index', new Date().getTime() + index)
            }
          })
        }
        if (res.configDepartmentList.length) {
          res.configDepartmentList.forEach((item, index) => {
            if (!item.index) {
              this.$set(item, 'index', new Date().getTime() + index)
            }
          })
        }
        if (res.configDepartmentMemberList.length) {
          res.configDepartmentMemberList.forEach((item, index) => {
            if (!item.index) {
              this.$set(item, 'index', new Date().getTime() + index)
            }
          })
        }
        if (this.$refs.Channelref) {
          res.configChannelList.forEach(el => {
            let region = '';
            el.regionList.forEach(item => {
              if (item.regionCode === 'all') {
                item.regionName = "全国";
              }
              region += item.regionName;
            });
            el.regionListRegionName = region;
          })
          this.$refs.Channelref.tableData.data = res.configChannelList
        }
        if (this.$refs.Departref) {
          res.configDepartmentList.forEach(el => {
            let region = "";
            el.regionList.forEach(item => {
              if (item.regionCode === 'all') {
                item.regionName = "全国";
              }
              region += item.regionName;
            });
            el.regionListRegionName = region;
          });
          this.$refs.Departref.tableData.data = res.configDepartmentList
        }
        if (this.$refs.Membersref) {
          res.configDepartmentMemberList.forEach(el => {
            let region = "";
            el.regionList.forEach(item => {
              if (item.regionCode === 'all') {
                item.regionName = "全国";
              }
              region += item.regionName;
            });
            el.regionListRegionName = region;
          });
          this.$refs.Membersref.tableData.data = res.configDepartmentMemberList
        }
      })
    },

    handleClick(tab, event) {
      console.log(tab, event);
    },

    inputradioGroup(val) {
      console.log(val)
    },

    async submitForm() {
      console.log('formList', this.formList)
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          this.configChannelListArr = [];
          this.configDepartListArr = [];
          this.configMembersListArr = [];

          if (this.formList.isSub == null || this.formList.isSub == 1) { // 按比例才校验
            let resolveFlag = await this.validateData()//按比例才校验--ratio必输
            if (!resolveFlag) return;

            //渠道返佣
            this.$refs.Channelref.tableData.data.forEach(item => {
              let regionCodeArr = []
              item.regionList.forEach(its => {
                regionCodeArr.push(its.regionCode)
              });

              let obj = {
                belongId: item.belongId ? item.belongId : item.id,
                belongName: item.name,
                ratio: item.ratio,
                regionCodeList: regionCodeArr,
                channelType: item.channelType,
                type: item.type,
                calculateRatio: item.calculateRatio
              };
              this.configChannelListArr.push(obj)
            });

            //部门绩效
            this.$refs.Departref.tableData.data.forEach(item => {
              let regionCodeArr = []
              item.regionList.forEach(its => {
                regionCodeArr.push(its.regionCode)
              })

              let obj = {
                belongId: item.belongId ? item.belongId : item.id,
                belongName: item.name,
                ratio: item.ratio,
                regionCodeList: regionCodeArr,
                type: item.type
              };
              this.configDepartListArr.push(obj)
            });

            //部门成员绩效
            this.$refs.Membersref.tableData.data.forEach(item => {
              let regionCodeArr = []
              item.regionList.forEach(its => {
                regionCodeArr.push(its.regionCode)
              })

              let obj = {
                belongId: item.belongId ? item.belongId : item.id,
                belongName: item.name,
                ratio: item.ratio,
                regionCodeList: regionCodeArr,
                type: item.type,
                serviceRatio: item.serviceRatio
              }
              this.configMembersListArr.push(obj)
            });
          }

          let obj = {
            configChannelList: this.configChannelListArr,
            configDepartmentList: this.configDepartListArr,
            configDepartmentMemberList: this.configMembersListArr,
            isSub: this.formList.isSub,
            productIdList: this.params.productId,
            retailStoreBrokerageFirstRatio: this.formList.retailStoreBrokerageFirstRatio || '0',
            retailStoreBrokerageSecondRatio: this.formList.retailStoreBrokerageSecondRatio || '0',
            maxBrokerage: this.formList.maxBrokerage || '0'
          };

          brokerageConfigSaveApi(obj).then(res => {
            console.info('save', res);

            if (res === true) {
              this.$message({ type: 'success', message: '操作成功' })
              this.cancelForm()
            } else {
              this.$message({ type: 'error', message: '操作失败' })
            }
          });
        } else {
          this.$message({ type: 'error', message: '请输入必填项' })
          return false;
        }
      });
    },

    cancelForm() {
      //取消关闭
      this.$emit("update:visible", false);
      this.$nextTick(() => {
        // this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },

    async validateData() {//提交前数据校验ration必输
      return new Promise((resolve, reject) => {
        let flag = false;

        if (this.$refs.Channelref.tableData.data.length) {
          let regionArr = [];
          this.$refs.Channelref.tableData.data.forEach(el => {
            el.regionList.forEach(item => {
              if (el.channelType === 2) {
                regionArr.push(item.regionCode);
              }
            });
          });

          if (regionArr.indexOf('all') >= 0 && regionArr.length > 1) {
            this.$message({
              message: '已有渠道商配置全国，一个地区只能配置一个渠道商',
              type: 'warning',
              showClose: true
            });
            resolve(false);
            flag = false;
          }

          // if (new Set(regionArr).size !== regionArr.length) {
          //   this.$message({
          //     message: '一个地区只能配置一个渠道商',
          //     type: 'warning',
          //     showClose: true
          //   });
          //   resolve(false);
          //   flag = false;
          // }

          if (this.$refs.Channelref.tableData.data.some(item => item.ratio === '')) {
            this.$message({ type: 'warning', message: '请输入渠道返佣佣金', showClose: true });
            resolve(false);
            flag = false;
          } else if (this.$refs.Channelref.tableData.data.some(item => item.regionList.length === 0)) {
            this.$message({ type: 'warning', message: '请选择渠道关联区域', showClose: true });
            resolve(false);
            flag = false;
          } else {
            flag = true;
          }
        }

        if (this.$refs.Departref.tableData.data.length) {
          if (this.$refs.Departref.tableData.data.some(item => item.ratio === '')) {
            this.$message({ type: 'warning', message: '请输入部门绩效', showClose: true });
            resolve(false);
            flag = false;
          } else if (this.$refs.Departref.tableData.data.some(item => item.regionList.length === 0)) {
            console.info('def depart');
            this.$message({ type: 'warning', message: '请选择部门关联区域', showClose: true });
            resolve(false);
            flag = false;
          } else {
            flag = true;
          }
        }

        if (this.$refs.Membersref.tableData.data.length) {
          if (this.$refs.Membersref.tableData.data.some(item => item.ratio === '')) {
            this.$message({ type: 'warning', message: '请输入部门成员绩效', showClose: true })
            resolve(false);
            flag = false;
          } else if (this.$refs.Membersref.tableData.data.some(item => item.regionList.length === 0)) {
            this.$message({ type: 'warning', message: '请选择部门成员关联区域', showClose: true });
            resolve(false);
            flag = false;
          } else {
            flag = true;
          }
        } else {
          flag = true
        }

        if (flag) {
          resolve(true)
        }
      })
    }
  }
}
</script>
