<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false" center @close="close">
    <div>
      <div class="step">
        <div class="title">知会阶段：</div>
        <div class="step-content">
          <div class="step-content-item" :class="{ active: setp == 1 }" @click="changStep(1)">一阶段</div>
          <div class="step-content-item" :class="{ active: setp == 2 }" @click="changStep(2)">二阶段</div>
          <div class="step-content-item" :class="{ active: setp == 3 }" @click="changStep(3)">三阶段</div>
        </div>
      </div>
      <div class="form">
        <el-form
          :model="form"
          :rules="rules"
          ref="ruleFormRef"
          label-width="120px"
          :disabled="formDisabled"
          v-loading="formLoading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行包信息" prop="packageId">
                <el-select filterable class="w100" v-model="form.packageId" placeholder="请选择执行包信息" @change="pkgChange">
                  <el-option v-for="item in redemptionPkgList" :label="item.scorePackageName" :value="item.id" :key="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行包名称" prop="pkgName">
                <el-input v-model="form.pkgName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行包总值" prop="pkgScore">
                <el-input v-model="form.pkgScore" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核通过积分值" prop="passedByNode6ScoreSum">
                <el-input v-model="form.passedByNode6ScoreSum" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" v-if="setp !== 1">
              <el-form-item label="监督扣减分值" prop="supervisionDeductScore">
                <el-input v-model="form.supervisionDeductScore" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可兑付分值" prop="availRdpScore">
                <div class="percent-number">
                  <el-input-number v-model="form.availRdpScore" disabled class="w100" :controls="false" :min="0"> </el-input-number>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="本次兑付分值" prop="currentRedemptionScore">
                <div class="percent-number">
                  <el-input-number
                    v-model="form.currentRedemptionScore"
                    :disabled="!form.packageId"
                    class="w100"
                    :controls="false"
                    :min="0"
                    :max="form.availRdpScore"
                    @blur="currentRedemptionScoreChange"
                  >
                  </el-input-number>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="本次兑付比例" prop="currentRedemptionRate">
                <div class="percent-number">
                  <el-input-number
                    v-model="form.currentRedemptionRate"
                    :disabled="!form.packageId"
                    class="w100"
                    :controls="false"
                    :min="0"
                    :max="100"
                    @blur="currentRedemptionRateChange"
                  /><span>%</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item>
              <Table1 v-if="dialogVisible" ref="table1" @totalPercentageChange="totalPercentageChange" />
            </el-form-item>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="实际兑付分值" prop="totalAmount">
                <div class="percent-number">
                  <el-input-number v-model="form.totalAmount" disabled class="w100" :controls="false" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="status">
        <div v-if="detailInfo.checkRemarks">
          事业部分管领导审核说明： <span>{{ detailInfo.checkRemarks }}</span>
        </div>
        <div v-if="detailInfo.acceptRemarks">
          服务商知会说明： <span>{{ detailInfo.acceptRemarks }}</span>
        </div>
      </div>
      <!-- 当前状态 -->
      <!-- <div class="status" v-if="type != 1">
        <div>
          当前状态： <span>{{ detailInfo.$checkState }}</span>
        </div>
      </div> -->
      <!-- 申诉原因 -->

      <div v-if="type == 3 && !detailInfo.accept">
        <el-form :model="confirmForm" :rules="confirmFormRules" ref="confirmFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" placeholder="请输入备注，最长500字" maxlength="500" v-model="confirmForm.remarks"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 审核意见 -->
      <div v-if="type == 4">
        <el-form :model="reviewForm" :rules="reviewFormRules" ref="reviewFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="审核意见" prop="checkResult">
            <el-radio-group v-model="reviewForm.checkResult">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="审批说明"
            prop="checkRemarks"
            :rules="[
              {
                required: !reviewForm.checkResult,
                message: '请输入审批说明',
                trigger: 'blur'
              }
            ]"
          >
            <el-input type="textarea" placeholder="请输入审核意见，最长500字" maxlength="500" v-model="reviewForm.checkRemarks"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 创建按钮 -->
    <span slot="footer" class="dialog-footer" v-if="type == 1">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submitInfo">确 定</el-button>
    </span>

    <!-- 审核按钮 -->
    <span slot="footer" class="dialog-footer" v-if="type == 3 && !detailInfo.accept">
      <el-button @click="confirmFn('ARGUE')">申 诉</el-button>
      <el-button type="primary" @click="confirmFn('CONFIRM')">通 过</el-button>
    </span>
    <!-- 分管领导按钮 -->
    <span slot="footer" class="dialog-footer" v-if="type == 4">
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" @click="checkFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  redemptionValStatApi,
  redemptionNoticeReadApi,
  redemptionNoticeCreate,
  redemptionNoticeConfirmApi,
  redemptionPkgListApi,
  redemptionoticeCheckApi
} from '@/api/distributeVoucher.js';
import { mapGetters } from 'vuex';
import Table1 from './table/table1.vue';

export default {
  components: { Table1 },
  data() {
    return {
      dialogVisible: false,
      type: '',
      currentRow: {},
      title: '新增',
      setp: 1,
      formDisabled: false,
      redemptionPkgList: [],
      form: {
        packageId: '',
        pkgName: '',
        pkgScore: '',
        passedByNode6ScoreSum: '',
        availRdpScore: 0,
        totalAmount: '',
        currentRedemptionScore: '',
        currentRedemptionRate: ''
      },
      rules: {
        currentRedemptionScore: [{ required: true, message: '请输入本次兑换分值', trigger: 'blur' }],
        currentRedemptionRate: [{ required: true, message: '请输入本次兑换分值', trigger: 'blur' }]
      },
      confirmForm: {
        remarks: ''
      },

      reviewForm: {
        checkRemarks: '',
        checkResult: ''
      },
      reviewFormRules: {
        checkResult: [{ required: true, message: '请选择审核意见', trigger: 'change' }]
      },
      confirmFormRules: {
        remarks: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      detailInfo: {},
      totalPercentageNums: 0,
      formLoading: false
    };
  },

  created() {
    this.getRedemptionPkgListApi();
  },
  methods: {
    async changStep(step) {
      this.formDisabled = true;
      this.setp = step;
      this.clearData();
      await this.getRedemptionPkgListApi();
      this.formDisabled = false;
    },
    clearData() {
      this.form = {
        packageId: '',
        pkgName: '',
        pkgScore: '',
        passedByNode6ScoreSum: '',
        availRdpScore: 0,
        totalAmount: '',
        currentRedemptionScore: '',
        currentRedemptionRate: ''
      };
      this.totalPercentageNums = 0;
      this.$refs.table1.initInfo();
    },
    totalPercentageChange(nums) {
      this.totalPercentageNums = nums;
      if (this.form.currentRedemptionScore) {
        const total = (this.form.currentRedemptionScore * nums) / 1000000;
        this.form.totalAmount = total;
      }
    },
    async getRedemptionPkgListApi() {
      const res = await redemptionPkgListApi(this.setp);
      this.redemptionPkgList = res.data.data;
    },
    // 创建知会
    createFn(type) {
      this.type = type;
      this.title = '新增';
      this.formDisabled = false;
      this.dialogVisible = true;
    },
    detail(row, type) {
      this.type = type;
      this.title = '查阅';
      this.detailInfo = row;
      if (type == 3 && row.noticeState != 'CONFIRM') {
        this.redemptionNoticeRead(row.noticeId);
      }
      let arr = [
        {
          id: row.packageId,
          scorePackageName: row.packageName
        }
      ];
      this.redemptionPkgList = arr;
      this.form.packageId = row.packageId;
      this.formDisabled = true;
      this.form.pkgName = row.packageName;
      this.form.pkgScore = row.packageScore;
      this.setp = row.step;
      this.form.availRdpScore = row.availRdpScore;
      this.form.supervisionDeductScore = row.supervisionDeductScore;
      this.form.passedByNode6ScoreSum = row.passedByNode6ScoreSum;
      this.form.currentRedemptionScore = row.currentRedemptionScore;
      this.form.currentRedemptionRate = row.currentRedemptionRate;

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.table1.redemptionFn(row.redemptionResult);
      });
    },
    review(row, type) {
      this.type = type;
      this.title = '审核';
      this.form.supervisionDeductScore = row.supervisionDeductScore;
      this.currentRow = row;
      this.formDisabled = true;
      this.setp = row.step;
      this.form.packageId = row.packageId;
      this.form.availRdpScore = row.availRdpScore;
      this.form.passedByNode6ScoreSum = row.passedByNode6ScoreSum;
      this.form.pkgName = row.packageName;
      this.form.pkgScore = row.packageScore;
      this.form.currentRedemptionScore = row.currentRedemptionScore;
      this.form.currentRedemptionRate = row.currentRedemptionRate;
      this.detailInfo = row;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.table1.redemptionFn(row.redemptionResult);
      });
    },
    pkgChange(e) {
      this.form.totalAmount = '';
      this.form.currentRedemptionScore = '';
      this.form.currentRedemptionRate = '';
      this.redemptionValStat(e);
    },
    async redemptionValStat(id) {
      this.formLoading = true;
      const res = await redemptionValStatApi(id);
      if (res.data.code === 0) {
        this.detailInfo = res.data.data;
        this.form.pkgName = res.data.data.pkgName;
        this.form.pkgScore = res.data.data.pkgScore;
        this.form.passedByNode6ScoreSum = res.data.data.passedByNode6ScoreSum;
        this.form.supervisionDeductScore = res.data.data.supervisionDeductScore;
        if (this.setp === 1) {
          this.form.availRdpScore = res.data.data.availRdpScore > 0 ? res.data.data.availRdpScore : 0;
        } else if (this.setp === 2) {
          this.form.availRdpScore = res.data.data.step2AvailRdpScore > 0 ? res.data.data.step2AvailRdpScore : 0;
        } else {
          this.form.availRdpScore = res.data.data.step3AvailRdpScore > 0 ? res.data.data.step3AvailRdpScore : 0;
        }

        this.$refs.table1.initInfo(this.detailInfo);
        if (res.data.data.taskApprovedScoreRateNinetyPercent) {
          this.$refs.table1.setInfo(res.data.data.taskApprovedScoreRateNinetyPercent);
        }
        this.formLoading = false;
      }
    },
    //  提交创建知会
    async submitInfo() {
      const items = this.$refs.table1.returnInfo();
      const obj = {
        packageId: this.detailInfo.id,
        step: this.setp,
        fromEntId: this.detailInfo.fromEntId,
        toEntId: this.detailInfo.toEntId,
        items: items,
        passedByNode6ScoreSum: this.form.passedByNode6ScoreSum,
        supervisionDeductScore: this.form.supervisionDeductScore,
        availRdpScore: this.form.availRdpScore,
        currentRedemptionScore: this.form.currentRedemptionScore,
        currentRedemptionRate: this.form.currentRedemptionRate,
        totalAmount: this.form.totalAmount,
        currentRedemptionTotal: items[0].totalPercentage
      };
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          const res = await redemptionNoticeCreate(obj);
          if (res.data.code === 0) {
            this.$message.success('新增成功');
            this.$emit('success');
            this.close();
          }
        }
      });
    },
    async redemptionNoticeRead(id) {
      redemptionNoticeReadApi({
        noticeId: id
      }).then((res) => {
        console.log('res', res);
      });
    },
    confirmFn(type) {
      this.$refs.confirmFormRef.validate(async (valid) => {
        if (valid) {
          const obj = {
            noticeId: this.detailInfo.noticeId,
            state: type,
            remarks: this.confirmForm.remarks
          };
          const res = await redemptionNoticeConfirmApi(obj);
          if (res.data.data) {
            this.$message.success('添加成功');
            this.close();
          }
        }
      });
    },
    checkFn() {
      this.$refs.reviewFormRef.validate(async (valid) => {
        if (valid) {
          let obj = this.reviewForm;
          obj.redemptionNoticeId = this.currentRow.noticeId;
          const res = await redemptionoticeCheckApi(this.reviewForm);
          if (res.data.data) {
            this.$message.success('审核成功！');
            this.close();
          }
        }
      });
    },
    close() {
      this.type = '';
      this.$refs.table1.resetFields();
      this.formDisabled = false;
      this.form = {
        pkgName: '',
        pkgScore: '',
        currentRedemptionScore: '',
        currentRedemptionRate: ''
      };
      if (this.$refs.reviewFormRef) {
        this.$refs.reviewFormRef.resetFields();
      }

      this.confirmForm.remarks = '';
      this.detailInfo = {};
      this.dialogVisible = false;
      this.$emit('success');
    },
    currentRedemptionScoreChange() {
      let e = this.form.currentRedemptionScore;
      if (e) {
        const currentRedemptionRate = (e / this.form.pkgScore) * 100;
        let num = currentRedemptionRate.toFixed(2);
        this.form.currentRedemptionRate = Number(num);
        if (this.totalPercentageNums && this.form.pkgScore) {
          this.totalPercentageChange(this.totalPercentageNums);
        }
      }
    },
    currentRedemptionRateChange() {
      let e = this.form.currentRedemptionRate;
      if (e) {
        const num = e / 100;
        this.form.currentRedemptionScore = num * this.form.pkgScore;
        if (this.totalPercentageNums && this.form.pkgScore) {
          this.totalPercentageChange(this.totalPercentageNums);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.form {
  margin-bottom: 10px;
  width: 100%;
}

.step {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-left: 35px;

  .title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    line-height: 18px;
    margin-right: 5px;
  }
  .step-content {
    display: flex;

    .step-content-item {
      margin-right: 10px;
      padding: 5px;
      line-height: 18px;
      border: 1px solid #dcdfe6;
      cursor: pointer;

      &.active {
        background: #6eb657;
        color: #fff;
      }
    }
  }
}

.percent-number {
  display: flex;
  align-items: center;

  span {
    color: #909399;
    position: absolute;
    right: 10px;
  }
}
.status {
  margin: 20px 0;

  span {
    font-weight: 400;
  }
}
</style>
