<template>
  <div :class="['assign-config', { 'is-disabled': loading }]">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="赋分公式：" prop="formula">
        <el-select
          v-model="modalForm.formula"
          placeholder="请选择"
          @change="formulaChange"
        >
          <el-option
            v-for="(val, key) in formulas"
            :key="key"
            :label="val"
            :value="key"
          ></el-option>
        </el-select>
        <div class="formula-tips" v-if="modalForm.formula">
          <div v-if="modalForm.formula === 'FORMULA1'">
            <p>赋值分=卷面成绩+ (100- 卷面成绩)/赋分系数</p>
          </div>
          <div v-if="modalForm.formula === 'FORMULA2'">
            <p>
              赋值分=ROUND(IF(初始卷面>=参数,55+(初始卷面-参数)/（初始卷面最高分-参数)*（x-55）,初始卷面*50/参数)*2,0)/2
            </p>
            <div>
              <span style="float: left">说明：</span>
              <div style="margin-left: 50px">
                <p>1.如果初始卷面最高的大于99时，则x=100，否则x=99；</p>
                <p>2.参数根据每次总体初始成绩的不及格率进行调整。</p>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        v-if="modalForm.formula === 'FORMULA1'"
        label="赋分系数："
        prop="detail"
      >
        <el-radio-group v-model="modalForm.all">
          <el-radio-button :label="true">统一设置</el-radio-button>
          <el-radio-button :label="false">按考查学院设置</el-radio-button>
        </el-radio-group>
        <el-checkbox
          v-model="modalForm.openRebuild"
          class="ml-4"
          @change="openRebuildChange"
          >重修单独设置赋分系数</el-checkbox
        >
        <el-checkbox class="ml-4" v-model="modalForm.openRound"
          >赋分后59分自动加1</el-checkbox
        >
        <el-checkbox v-model="modalForm.openTotalScoreRound"
          >原始分四舍五入</el-checkbox
        >
        <el-checkbox v-model="modalForm.open54To53"
          >赋分后等于54分调整赋分分值为53</el-checkbox
        >
        <el-checkbox v-model="modalForm.open54d5"
          >赋分后如果小于等于54.5的取原始分值</el-checkbox
        >
      </el-form-item>
      <el-form-item v-if="modalForm.formula === 'FORMULA1'">
        <div v-if="modalForm.all">
          <el-input-number
            v-model.number="modalForm.value"
            :min="0"
            :controls="false"
            placeholder="赋分系数"
            @change="allRateChange"
          ></el-input-number>
          <el-input-number
            v-if="modalForm.openRebuild"
            v-model.number="modalForm.rebuildValue"
            class="ml-2"
            :min="0"
            :controls="false"
            placeholder="重修赋分系数"
            @change="allRateReChange"
          ></el-input-number>
        </div>
        <div v-else class="rate-details">
          <div
            class="rate-detail"
            v-for="item in modalForm.detail"
            :key="item.college"
          >
            <div class="rate-detail-label">{{ item.college }}</div>
            <div class="rate-detail-content">
              <el-input-number
                v-model.number="item.value"
                :min="0"
                :controls="false"
                placeholder="赋分系数"
              ></el-input-number>
              <el-input-number
                v-if="modalForm.openRebuild"
                v-model.number="item.rebuildValue"
                class="ml-2"
                :min="0"
                :controls="false"
                placeholder="重修赋分系数"
              ></el-input-number>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="modalForm.formula === 'FORMULA2'" label="规则：">
        <el-checkbox v-model="modalForm.openFetchOriginScore"
          >赋分后小于原始分值取原始分值</el-checkbox
        >
      </el-form-item>
      <el-form-item
        v-if="modalForm.formula === 'FORMULA2'"
        label="参数："
        prop="detail"
      >
        <el-input-number
          v-model.number="modalForm.value"
          :min="0"
          :controls="false"
          placeholder="请填写参数"
          @change="allRateChange"
        ></el-input-number>
      </el-form-item>
      <el-form-item>
        <div class="mb-1">
          <el-button type="primary" :loading="loading" @click="toCalc">{{
            loading ? "正在计算中" : "开始试算"
          }}</el-button>
          <!-- <el-button
            type="primary"
            :loading="publishing"
            :disabled="!modalForm.id"
            @click="toPublish"
            >发布</el-button
          > -->
        </div>
        <div>
          <span
            >计算状态：<i>{{ ASSIGN_CALC_STATUS[detailData.status] }}</i></span
          >
          <span class="ml-4"
            >发布状态：<i :class="{ 'color-success': detailData.publish }">{{
              detailData.publish ? "已发布" : "未发布"
            }}</i></span
          >
        </div>
        <p v-if="detailData.errorMsg" class="tips-info tips-error">
          计算结果：失败，错误信息：{{ detailData.errorMsg }}
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import timeMixin from "@/mixins/timeMixin";
import {
  assignmentDetailInfo,
  assignmentCalculate,
  assignmentPublish,
} from "../../api";
import { ASSIGN_CALC_STATUS } from "@/constants/enumerate";

export default {
  name: "assign-config",
  mixins: [timeMixin],
  props: {
    detailInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    assignInfo: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: {
        id: null,
        formula: "",
        all: true,
        openRebuild: false,
        value: undefined,
        rebuildValue: undefined,
        openRound: false,
        openTotalScoreRound: false,
        detail: [],
        open54To53: false,
        open54d5: false,
        openFetchOriginScore: false,
      },
      formulas: {
        FORMULA1: "公式1",
        FORMULA2: "公式2",
      },
      ASSIGN_CALC_STATUS,
      rules: {
        formula: [
          {
            required: true,
            message: "请选择赋分公式",
            trigger: "change",
          },
        ],
        detail: [
          {
            validator: (rule, value, callback) => {
              if (value.some((item) => !item.value)) {
                return callback(new Error(`完成参数设置`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
      loading: false,
      publishing: false,
      statusPeriod: 5000,
      detailData: {},
    };
  },
  mounted() {
    this.modalForm.id = this.detailInfo.id;
    this.modalForm.formula = this.detailInfo.formula;
    this.modalForm.openRound = this.detailInfo.openRound;
    this.modalForm.openTotalScoreRound = this.detailInfo.openTotalScoreRound;
    if (this.detailInfo.coefficient) {
      const coefficient = JSON.parse(this.detailInfo.coefficient);
      this.modalForm.all = coefficient.all;
      this.modalForm.openRebuild = coefficient.openRebuild;
      this.modalForm.value = coefficient.value;
      this.modalForm.rebuildValue = coefficient.rebuildValue;
      this.modalForm.open54To53 = coefficient.open54To53;
      this.modalForm.open54d5 = coefficient.open54d5;
      this.modalForm.openFetchOriginScore = coefficient.openFetchOriginScore;
      this.modalForm.detail = coefficient.detail || [];
    }
    this.detailData = { ...this.detailInfo };
    if (!this.modalForm.detail.length) {
      this.modalForm.detail = this.detailInfo.inspectCollege.map((item) => {
        return {
          college: item,
          value: undefined,
          rebuildValue: undefined,
        };
      });
    }
    this.loading = this.detailInfo.status === "RUNNING";
    if (!this.loading) return;
    this.addSetTime(() => {
      this.getData();
    }, this.statusPeriod);
  },
  beforeDestroy() {
    this.clearSetTs();
  },
  methods: {
    async getData() {
      this.clearSetTs();
      const res = await assignmentDetailInfo(this.assignInfo, true);
      this.loading = res.status === "RUNNING";
      this.modalForm.id = res.id;
      this.detailData = res;

      if (!this.loading) {
        this.$message.success("计算完成！");
        return;
      }

      this.addSetTime(() => {
        this.getData();
      }, this.statusPeriod);
    },
    formulaChange(val) {
      if (val === "FORMULA2") {
        this.modalForm.all = true;
      }
      this.modalForm.value = undefined;
      this.allRateChange(this.modalForm.value);
    },
    allRateChange(val) {
      this.modalForm.detail.forEach((item) => {
        item.value = val;
      });
    },
    allRateReChange(val) {
      this.modalForm.detail.forEach((item) => {
        item.rebuildValue = val;
      });
    },
    openRebuildChange(val) {
      if (!val) this.modalForm.rebuildValue = undefined;

      this.modalForm.detail.forEach((item) => {
        item.rebuildValue =
          val && this.modalForm.rebuildValue
            ? this.modalForm.rebuildValue
            : undefined;
      });
    },
    async toPublish() {
      if (!this.modalForm.id || this.detailData.status !== "FINISH") {
        return;
      }
      const result = await this.$confirm(`确定要发布赋分成绩吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;

      if (this.publishing) return;
      this.publishing = true;

      const res = await assignmentPublish(this.modalForm.id).catch(() => {});
      this.publishing = false;
      if (!res) return;
      this.$message.success("发布成功！");
    },
    async toCalc() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;

      const datas = {
        ...this.assignInfo,
        id: this.modalForm.id,
        formula: this.modalForm.formula,
        openRound: this.modalForm.openRound,
        openTotalScoreRound: this.modalForm.openTotalScoreRound,
        coefficient: this.modalForm,
      };
      this.detailData.errorMsg = "";
      const data = await assignmentCalculate(datas).catch(() => {});
      if (!data) {
        this.loading = false;
        return;
      }
      this.$message.success("提交成功，正在计算中……");
      this.addSetTime(() => {
        this.getData();
      }, this.statusPeriod);
    },
  },
};
</script>
