<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="65%" center :close-on-click-modal="false" :before-close="beforeClose" @clsoe="dialogClose">
    <div>
      <div class="message">
        本系统中的年度服务目标、【年度服务预算】、年度服务计划等，无论是否经由一方或双方同意或者确认，均不构成双方之间的协议；服务量、服务费用价格与金额等应以另行签署的合同为准。
      </div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" :disabled="formDisabled">
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标产品" :prop="type === 'add' ? 'skuId' : 'skuName'">
              <el-select v-if="type === 'add'" v-model="form.skuId" placeholder="下拉选择" class="w100" @change="skuIdChange">
                <el-option v-for="item in drugList" :key="item.drug_id" :label="item.drug_name" :value="item.drug_id"></el-option>
              </el-select>
              <el-input v-else v-model="form.skuName" placeholder="目标产品" :disabled="formItemDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产企业" prop="ent_name">
              <el-input v-model="form.ent_name" placeholder="生产企业" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标总值" prop="planScore">
              <el-input v-model="form.planScore"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承接对象" prop="consigneeId">
              <el-select v-model="form.consigneeId" placeholder="下拉选择" class="w100" @change="consigneeIdChange">
                <el-option v-for="item in csoList" :key="item.deptId" :label="item.name" :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标类型" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择" class="w100" :disabled="formItemDisabled" @change="planTypeChange">
                <el-option label="年度计划" value="ANN" />
                <el-option label="季度计划" value="QRT" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标周期" prop="monthrange">
              <template v-if="form.planType === ''">
                <el-date-picker disabled class="w100" type="year" placeholder="请选择" value-format="yyyy"></el-date-picker>
              </template>
              <template v-else-if="form.planType === 'ANN'">
                <el-date-picker class="w100" :disabled="formItemDisabled" v-model="form.monthrange" type="year" @change="monthrangeChange" placeholder="请选择" value-format="yyyy">
                </el-date-picker>
              </template>
              <template v-else-if="form.planType === 'QRT'">
                <ElQuarterPicker :disabled="formItemDisabled" placeholder="请选择" v-model="form.monthrange" @change="monthrangeChange" class="w100" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="目标名称" prop="planName">
              <el-input v-model="form.planName" placeholder="目标名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-if="type === 'distribute'">
        剩余积分值： {{ form.availScore }}
      </template>
      <!-- 审核说明表单 -->
      <el-form class="reviewForm" v-if="type === 'review' || type === 'dismantleReview'" :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item
          label="审核说明"
          prop="msg"
          :rules="[
            {
              required: reviewFormMsgRequired,
              message: '请填写审核说明',
              trigger: 'blur'
            }
          ]"
        >
          <el-input type="textarea" v-model="reviewForm.msg"></el-input>
        </el-form-item>
      </el-form>

      <!-- 拆解 -->
      <div v-if="type === 'dismantle'">
        <dismantleTable :planScore="form.planScore" ref="dismantleTableTable" />
      </div>

      <!-- 拆解审核 -->
      <div v-if="type === 'dismantleReview' || type === 'statistics'">
        <tableDate :planScore="form.planScore" :propsTableData="dismantleReviewData" />
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <!-- 药企新增 || 区域分发 -->
      <template v-if="type === 'add' || type === 'distribute'">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
      <template v-if="type === 'review'">
        <el-button @click="reviewClick(false)">拒绝</el-button>
        <el-button type="primary" @click="reviewClick(true)">通过</el-button>
      </template>
      <template v-if="type === 'dismantle'">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="dismantleSubmit">提交</el-button>
      </template>
      <template v-if="type === 'dismantleReview'">
        <el-button @click="dismantleReviewSubmt(false)">拒绝</el-button>
        <el-button type="primary" @click="dismantleReviewSubmt(true)">通过</el-button>
      </template>
      <template v-if="type === 'statistics'">
        <el-button @click="dialogClose">关闭</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import dayjs from 'dayjs';
import ElQuarterPicker from '@/components/ElQuarterPicker/index';
import dismantleTable from './dismantleTable.vue';
import tableDate from './tableDate.vue';
import {createListApi, planCheckApi, planDetailCreateApi, getPlanDetailsApi, checkPlanDetailsApi, planUpdateApi, getListDescendantApi} from '@/api/wmdeptbudget/plan.js';

import {getListDrugApi} from '@/api/assignPoints/currency/index';
import {listCsoApi} from '@/api/csmpages/index.js';

export default {
  components: {dismantleTable, tableDate, ElQuarterPicker},
  data() {
    return {
      btnType: '',
      type: 'add',
      currentRow: {},
      title: '新增',
      dismantleReviewData: [],
      detailsState: '',
      dialogVisible: false,
      formDisabled: false,
      formItemDisabled: false,
      drugList: [],
      csoList: [],
      value1: [],
      planIssueRange: '',
      planExpiryRange: '',
      form: {
        planType: '',
        parentId: 0,
        skuId: '',
        ent_name: '',
        planName: '',
        planScore: '',
        monthrange: '2024',
        consigneeId: '',
        planIssue: '',
        planExpiry: '',
        locFlag: 'UN_LOCK'
      },

      rules: {
        skuId: [{required: true, message: '请填写生产企业', trigger: 'blur'}],
        planName: [{required: true, message: '请填写目标名称', trigger: 'blur'}],
        monthrange: [{required: true, message: '请选择目标周期'}],
        consigneeId: [{required: true, message: '请选择承接对象', trigger: 'blur'}],
        planScore: [{required: true, message: '请填写目标总值', trigger: 'blur'}],
        planType: [{required: true, message: '请选择承接对象', trigger: 'blur'}]
      },
      reviewForm: {
        msg: ''
      },
      reviewFormMsgRequired: false,

      pickerOptions: {
        disabledDate: time => {
          // 使用箭头函数保持this上下文
          const planIssueDate = new Date(this.planIssueRange);
          const planExpiryDate = new Date(this.planExpiryRange);
          return time.getTime() <= planIssueDate.getTime() || time.getTime() >= planExpiryDate.getTime();
        }
      }
    };
  },
  methods: {
    async getDrugList() {
      const res = await getListDrugApi();
      this.drugList = res.data.data;
    },
    async getCsoList() {
      const res = await getListDescendantApi();
      this.csoList = res.data.data;
    },
    skuIdChange(e) {
      if (e) {
        const curr = this.drugList.find(item => item.drug_id === e);
        if (curr) this.form.ent_name = curr.ent_name;
      }
      this.nameChange();
    },
    nameChange() {
      if (this.form.skuId && this.form.consigneeId && this.form.planType && this.form.planExpiry && this.form.planIssue) {
        let skuIdName;
        let consigneeIdName;
        if (this.form.skuId && this.form.consigneeId) {
          skuIdName = this.drugList.find(item => item.drug_id === this.form.skuId);
          consigneeIdName = this.csoList.find(item => item.deptId === this.form.consigneeId);
        }
        if (this.form.planType === 'ANN') {
          if (skuIdName && consigneeIdName) {
            const name = `${this.form.monthrange}年度-全年-${consigneeIdName.name}-${skuIdName.drug_name}`;
            this.form.planName = name;
          }
        } else {
          const arr = this.form.monthrange.split('-');
          let text;
          switch (arr[1]) {
            case '01':
              text = '第一';
              break;
            case '02':
              text = '第二';
              break;
            case '03':
              text = '第三';
              break;
            case '04':
              text = '第四';
              break;
          }
          const name = `${arr[0]}年度-${text}季度-${consigneeIdName.name}-${skuIdName.drug_name}`;
          this.form.planName = name;
        }
      }
    },
    confirm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 判断如果是编辑 走编辑接口

          // 分发限制目标总值不能超过剩余积分值
          if (this.type === 'distribute') {
            if (this.form.planScore > this.form.availScore) {
              return this.$message.info('当前分发目标总值不能超过剩余积分值！');
            }
          }
          if (this.btnType === 'edit') {
            return this.updateConfirm();
          }

          const res = await createListApi(this.form);
          if (res.data.data) {
            this.$message.success('添加成功');
            this.$emit('updateList');
            this.dialogClose();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async updateConfirm() {
      const obj = Object.assign(this.form, {
        planId: this.currentRow.planId
      });

      const res = await planUpdateApi(obj);
      if (res.data.data) {
        this.$message.success('编辑成功');
        this.$emit('updateList');
        this.dialogClose();
      }
    },
    getQuarterRange(dateString) {
      const [year, quarterCode] = dateString.split('-').map(Number);
      let startMonth, endMonth, endDay;
      switch (quarterCode) {
        case 1: // Q1
          startMonth = 1;
          endMonth = 3;
          endDay = 31;
          break;
        case 2: // Q2
          startMonth = 4;
          endMonth = 6;
          endDay = 30;
          break;
        case 3: // Q3
          startMonth = 7;
          endMonth = 9;
          endDay = 30;
          break;
        case 4: // Q4
          startMonth = 10;
          endMonth = 12;
          endDay = 31;
          break;
        default:
          throw new Error('Invalid quarter code');
      }
      const startDate = `${year}-${String(startMonth).padStart(2, '0')}-01`;
      const endDate = `${year}-${String(endMonth).padStart(2, '0')}-${endDay}`;
      return [startDate, endDate];
    },
    planTypeChange() {
      this.form.monthrange = '';
      this.form.planIssue = '';
      this.form.planExpiry = '';
      this.form.planName = '';
    },

    monthrangeChange(e) {
      console.log('e', e);
      let skuIdName;
      let consigneeIdName;
      if (this.form.skuId && this.form.consigneeId) {
        skuIdName = this.drugList.find(item => item.drug_id === this.form.skuId);
        consigneeIdName = this.csoList.find(item => item.deptId === this.form.consigneeId);
      }
      if (this.form.planType === 'ANN') {
        this.form.planIssue = e + '-01-01';
        this.form.planExpiry = e + '-12-31';
        if (skuIdName && consigneeIdName) {
          const name = `${e}年度-全年-${consigneeIdName.name}-${skuIdName.drug_name}`;
          this.form.planName = name;
        }
      } else if (this.form.planType === 'QRT') {
        if (skuIdName && consigneeIdName) {
          const arr = e.split('-');
          let text;
          switch (arr[1]) {
            case '01':
              text = '第一';
              break;
            case '02':
              text = '第二';
              break;
            case '03':
              text = '第三';
              break;
            case '04':
              text = '第四';
              break;
          }
          const name = `${arr[0]}年度-${text}季度-${consigneeIdName.name}-${skuIdName.drug_name}`;
          this.form.planName = name;
        }

        let arr = this.getQuarterRange(e);
        this.form.planIssue = arr[0];
        this.form.planExpiry = arr[1];
      }
    },
    beforeClose(done) {
      this.dialogClose();
    },
    dialogClose() {
      this.formDisabled = false;
      this.formItemDisabled = false;
      this.type = '';
      this.title = '';
      this.dismantleReviewData = [];
      this.detailsState = '';
      this.btnType = '';
      this.$refs.ruleForm.resetFields();
      const obj = {
        planType: '',
        parentId: 0,
        skuId: '',
        planName: '',
        planScore: '',
        monthrange: '',
        consigneeId: '',
        planIssue: '',
        planExpiry: '',
        locFlag: 'UN_LOCK'
      };
      this.$set(this, 'form', obj);
      this.reviewForm.msg = '';
      this.dialogVisible = false;
    },
    addBtn() {
      this.getDrugList();
      this.getCsoList();
      this.formDisabled = false;
      this.dialogVisible = true;
      this.type = 'add';
      this.title = '新增';
    },

    getQuarterCodeByDate(dateString) {
      const [year, month] = dateString.split('-').map(Number);
      let quarterCode;
      if (month >= 1 && month <= 3) {
        quarterCode = 1; // Q1
      } else if (month >= 4 && month <= 6) {
        quarterCode = 2; // Q2
      } else if (month >= 7 && month <= 9) {
        quarterCode = 3; // Q3
      } else if (month >= 10 && month <= 12) {
        quarterCode = 4; // Q4
      } else {
        throw new Error('Invalid month value');
      }
      return `${year}-0${quarterCode}`;
    },

    initForm(row) {
      // 年度计划
      if (row.planType === 'ANN') {
        const year = row.planIssue.slice(0, 4);
        row.monthrange = year;
      }
      if (row.planType === 'QRT') {
        const str = this.getQuarterCodeByDate(row.planIssue);
        row.monthrange = str;
      }

      if (row.skuInfo) {
        row.ent_name = row.skuInfo.manufacturer;
        row.skuName = row.skuInfo.skuName;
      }

      this.form = row;
      this.dialogVisible = true;
    },
    // 审核  0 事业部上级审核
    reviewFn(row) {
      this.title = '审核';
      this.type = 'review';
      const arr = [
        {
          name: row.consigneeName,
          deptId: row.consigneeId
        }
      ];
      this.csoList = arr;
      this.formDisabled = true;
      row.consigneeId = Number(row.consigneeId);
      this.initForm(row);
    },
    reviewClick(result) {
      this.reviewFormMsgRequired = !result;
      this.$nextTick(() => {
        this.$refs.reviewFormRef.validate(async valid => {
          if (valid) {
            const obj = {
              planId: this.form.planId,
              result: result,
              msg: this.reviewForm.msg
            };
            const res = await planCheckApi(obj);
            if (res.data.data) {
              this.$message.success('审核提交成功');
              this.$emit('updateList');
              this.dialogClose();
            }
            console.log('res', res);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      });
    },
    // 分发
    distributeFn(row) {
      this.type = 'distribute';
      this.currentRow = row;
      this.title = '分发';
      this.getCsoList();
      this.formItemDisabled = true;
      if (row.skuInfo) {
        this.form.ent_name = row.skuInfo.manufacturer;
        this.form.skuName = row.skuInfo.skuName;
        this.form.skuId = row.skuInfo.skuId;
      }
      this.form.parentId = row.planId;
      this.form.availScore = row.availScore;
      this.form.planType = row.planType;
      this.form.planIssue = row.planIssue;
      this.form.planExpiry = row.planExpiry;
      // 年度计划
      if (row.planType === 'ANN') {
        const year = row.planIssue.slice(0, 4);
        this.form.monthrange = year;
      }
      if (row.planType === 'QRT') {
        const str = this.getQuarterCodeByDate(row.planIssue);
        this.form.monthrange = str;
      }
      this.dialogVisible = true;
    },
    consigneeIdChange(e) {
      if (this.type === 'distribute') {
        if (e) {
          const consigneeIdName = this.csoList.find(item => item.deptId === e);
          const name = this.currentRow.planName + '-' + consigneeIdName.name;
          this.form.planName = name;
        }
      }
      this.nameChange();
    },
    // 拆解
    dismantleFn(row) {
      this.type = 'dismantle';
      this.form.planType = row.planType;
      const arr = [
        {
          name: row.consigneeName,
          deptId: row.consigneeId
        }
      ];
      this.csoList = arr;
      this.initForm(row);
      row.consigneeId = Number(row.consigneeId);
      this.formDisabled = true;
    },
    async dismantleSubmit() {
      const data = this.$refs.dismantleTableTable.tableData;

      const allQty = data.reduce((prev, curr) => prev + curr.qty, 0);
      const allTotal = data.reduce((prev, curr) => prev + curr.subtotal, 0);

      if (allTotal != this.form.planScore) {
        return this.$message.info('拆解总任务分值需等于目标总值');
      }
      const obj = {
        planId: this.form.planId,
        qty: allQty,
        total: allTotal,
        items: data
      };
      const res = await planDetailCreateApi(obj);
      if (res.data.data) {
        this.$message.success('拆解积分包成功');
        this.$emit('updateList');
        this.beforeClose();
      }
    },
    // 拆解审核
    dismantleReviewFn(row) {
      this.statisticsFn(row);
      this.type = 'dismantleReview';
      this.title = '拆解审核';
    },

    // 拆解审核提交
    dismantleReviewSubmt(type) {
      this.reviewFormMsgRequired = !type;
      this.$nextTick(() => {
        this.$refs.reviewFormRef.validate(async valid => {
          if (valid) {
            const obj = {
              detailsId: this.form.planDetails.detailsId,
              result: type,
              msg: this.reviewForm.msg,
              currentState: this.detailsState
            };
            const res = await checkPlanDetailsApi(obj);
            if (res.data.data) {
              this.$message.success('审核提交成功');
              this.$emit('updateList');
              this.dialogClose();
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      });
    },
    // 获取拆解详情数据
    async getPlanDetails(id) {
      const res = await getPlanDetailsApi(id);
      if (res.data.code === 0) {
        this.dismantleReviewData = res.data.data.items;
        this.detailsState = res.data.data.detailsState;
      }
    },
    // 数据统计
    statisticsFn(row) {
      this.title = '数据统计';
      this.type = 'statistics';
      this.formDisabled = true;
      if (row.planDetails.detailsId) {
        this.getPlanDetails(row.planDetails.detailsId);
      }
      const arr = [
        {
          name: row.consigneeName,
          deptId: row.consignorId
        }
      ];
      this.csoList = arr;
      row.consigneeId = Number(row.consignorId);
      this.initForm(row);
      this.dialogVisible = true;
    },
    async editFn(row, type) {
      console.log('row', row);

      if (row.parentId == 0) {
        this.type = 'add';
      } else {
        this.type = 'distribute';
        this.formItemDisabled = true;
        if (row.planState == 'INIT') {
          row.availScore = row.parentPlanAvailScore + row.planScore;
        } else if (row.planState == 'REJECTED') {
          row.availScore = row.parentPlanAvailScore;
        }
      }
      this.currentRow = row;
      this.btnType = 'edit';

      await this.getDrugList();
      await this.getCsoList();
      row.skuId = row.skuId + '';
      this.skuIdChange(row.skuId);
      this.form = row;
      if (this.type === 'distribute') {
        this.form.ent_name = row.skuInfo.manufacturer;
        this.form.skuName = row.skuInfo.skuName;
        this.form.skuId = row.skuInfo.skuId;
      }
      // 年度计划
      if (row.planType === 'ANN') {
        const arr = row.planIssue.split('-');
        this.$set(this.form, 'monthrange', arr[0]);
      } else {
        const str = this.convertToQuarterStart(row.planIssue);
        this.$set(this.form, 'monthrange', str);
      }
      this.dialogVisible = true;
    },
    convertToQuarterStart(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = date.getMonth(); // 0 为 1 月，11 为 12 月
      // 根据月份计算季度开始月份
      let quarterStartMonth;
      if (month >= 0 && month <= 2) {
        quarterStartMonth = '01'; // Q1: 1月
      } else if (month >= 3 && month <= 5) {
        quarterStartMonth = '02'; // Q2: 4月
      } else if (month >= 6 && month <= 8) {
        quarterStartMonth = '03'; // Q3: 7月
      } else {
        quarterStartMonth = '04'; // Q4: 10月
      }
      return `${year}-${quarterStartMonth}`;
    }
  }
};
</script>
<style lang="scss" scoped>
.message {
  margin-bottom: 20px;
  border-radius: 10px;
  border: 1px solid #ccc;
  line-height: 35px;
  margin-left: 20px;
  padding: 10px 20px;
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}
</style>
