<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false" center @close="close">
    <div>
      <div class="form">
        <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="120px" :disabled="formDisabled">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行包信息" prop="packageId">
                <el-select 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="currentRedemptionScore">
                <div class="percent-number">
                  <el-input-number v-model="form.currentRedemptionScore" :disabled="!form.packageId" class="w100" :controls="false" :min="0" @blur="currentRedemptionScoreChange">
                  </el-input-number>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <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: '新增',
      formDisabled: false,
      redemptionPkgList: [],
      form: {
        packageId: '',
        pkgName: '',
        pkgScore: '',
        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
    };
  },

  created() {
    this.getRedemptionPkgListApi();
  },
  methods: {
    totalPercentageChange(nums) {
      this.totalPercentageNums = nums;
      if (this.form.currentRedemptionScore) {
        const total = (this.form.currentRedemptionScore * nums) / 1000000;
        console.log('total', total);

        this.form.totalAmount = total;
      }
    },
    async getRedemptionPkgListApi() {
      const res = await redemptionPkgListApi();
      this.redemptionPkgList = res.data.data;
    },
    show(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);
      }
      this.formDisabled = true;
      this.form.pkgName = row.packageName;
      this.form.pkgScore = row.packageScore;
      this.form.currentRedemptionScore = row.currentRedemptionScore;
      this.form.currentRedemptionRate = row.currentRedemptionRate;

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.table1.redemptionFn(row.redemptionResult);
      });
    },
    review(row, type) {
      console.log('row', row);

      this.type = type;
      this.title = '审核';
      this.currentRow = row;
      this.formDisabled = true;
      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.redemptionValStat(e);
    },
    async redemptionValStat(id) {
      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.$refs.table1.initInfo(this.detailInfo);
      }
    },
    async submitInfo() {
      const items = this.$refs.table1.returnInfo();
      const obj = {
        packageId: this.detailInfo.id,
        step: this.detailInfo.nextStep,
        fromEntId: this.detailInfo.fromEntId,
        toEntId: this.detailInfo.toEntId,
        items: items,
        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.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%;
}

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

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

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