<template>
  <div class="create-train gy-form">
    <h2 class="v-title">基本设置</h2>
    <div class="selft-form">
      <div style="width: 30%; min-width: 280px">
        <div class="selft-form-item">
          <div class="form-item-label">训练名称:</div>
          <div class="form-item-content">
            <el-input
              style="width: 100%; min-width: 200px"
              v-model="form.name"
              :maxlength="30"
              show-word-limit
            ></el-input>
          </div>
        </div>
        <div class="selft-form-item">
          <div class="form-item-label">训练类型:</div>
          <div class="form-item-content">
            <el-cascader
              style="width: 100%; min-width: 200px"
              :props="{ emitPath: false, value: 'id', label: 'name' }"
              v-model="form.type"
              @change="getSubjectList"
              :options="subjectTypeList"
            ></el-cascader>
          </div>
        </div>
      </div>
      <div
        class="selft-form-item-height"
        style="width: 70%; padding-left: 10px"
      >
        <div class="form-item-label">训练描述:</div>
        <div class="form-item-content">
          <el-input
            placeholder="请输入"
            style="height: 85px; min-width: 200px"
            type="textarea"
            maxlength="300"
            class="custom-input"
            show-word-limit
            v-model="form.comment"
          ></el-input>
        </div>
      </div>
      <div class="selft-form-item" style="width: 30%; min-width: 280px">
        <div class="form-item-label">训练科目:</div>
        <div class="form-item-content">
          <el-select
            v-model="form.subject"
            placeholder="请选择"
            style="min-width: 200px; width: 100%"
            @change="subjectChange"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div
        class="selft-form-item-height"
        style="width: 100%"
        v-if="checkedSubject"
      >
        <div class="form-item-label">科目说明:</div>
        <div class="form-item-content">
          <el-input
            disabled
            placeholder="请输入"
            style="height: 85px"
            type="textarea"
            v-model="checkedSubject.comment"
          ></el-input>
        </div>
      </div>
    </div>
    <h2 class="v-title" v-if="checkedSubject">操作设置</h2>
    <OperationSettiing1
      :anewSubjectId="anewSubjectId"
      :form="form"
      @userjudeRuleChage="userjudeRuleChage"
      :trainRules="trainRules"
      v-if="checkedSubject"
      :subjectInfo="checkedSubject"
      :groupInfo="groupInfo"
    ></OperationSettiing1>
    <h2 class="v-title">训练设置</h2>
    <div class="selft-form-item">
      <div class="form-item-label">训练引导:</div>
      <div class="form-item-content">
        <el-checkbox v-model="form.guide" :true-label="1" :false-label="0"
          >开启</el-checkbox
        >
      </div>
    </div>
    <div class="selft-form-item">
      <div class="form-item-label">训练时长:</div>
      <div class="form-item-content">
        <el-radio v-model="form.duration" :label="0">不限</el-radio>
        <el-radio v-model="form.duration" :label="1" style="margin-right: 5px"
          >计划</el-radio
        >

        <el-input-number
          v-if="form.duration"
          size="mini"
          style="width: 100px"
          v-model="form.durationNumber"
          controls-position="right"
          @change="handleChange"
          :min="10"
        />
        <span v-if="form.duration" style="margin-left: 5px">分钟</span>
      </div>
    </div>
    <h2 class="v-title" v-if="checkedSubject">评判设置</h2>
    <JudgRuleSetting
      v-if="checkedSubject"
      :form="form"
      :trainRules="trainRules"
    ></JudgRuleSetting>
    <div class="page-floor" v-if="checkedSubject">
      <el-button type="primary" @click="submit">等待训练</el-button>
    </div>
  </div>
</template>

<script>
import { getSubjectTypeApi, pagingGetSubjectApi } from "@/api/training/subject";
import OperationSettiing1 from "./components/OperationSetting1.vue";
import JudgRuleSetting from "./components/JudgRuleSetting.vue";
import "@/views/assessment-evaluation/utils/gyStyle.scss";
import { createTrainApi, getTrainDetailsApi } from "@/api/training/train";
export default {
  components: { OperationSettiing1, JudgRuleSetting },
  data() {
    return {
      form: { durationNumber: 0, duration: 0, guide: 0 },
      subjectTypeList: [],
      subjectList: [],
      checkedSubject: null,
      groupInfo: [],
      anewSubjectId: null,
      trainRules: {
        // 1-自动 2-人工
        judgmentShape: 2,
        automaticScoring: [
          { name: "组长考核规则", id: 1, disabled: false, percentageList: [] },
          { name: "组员考核规则", id: 2, disabled: false, percentage: 1 },
        ],
        manualScoring: { name: "自动评分", id: 3, percentage: 0.8 },
      },
      writeErrorList: [],
    };
  },
  created() {
    this.initData();
  },
  activated() {
    this.initData();
  },
  methods: {
    async initData() {
      if (this.$route.query.anewId) {
        const { data } = await getTrainDetailsApi(+this.$route.query.anewId);
        this.form = data;
        this.form.name = "";
        this.anewSubjectId = this.form.subject;
        if (+this.form.duration) {
          this.form.durationNumber = this.form.duration;
          this.form.duration = 1;
        } else {
          this.form.duration = 0;
        }
        await this.getSubjectList();
      }
      this.getTrainType();
    },
    async getTrainType() {
      const { data } = await getSubjectTypeApi();
      this.subjectTypeMap = data.toTree();
      this.subjectTypeList = this.subjectTypeMap.tree;
    },
    async getSubjectList() {
      const { data } = await pagingGetSubjectApi({
        train: this.form.type,
        status: 1,
        currentPage: 0,
        pageSize: 0,
      });
      this.subjectList = data.data;
      if (this.$route.query.anewId) {
        this.subjectChange(this.form.subject);
      }
    },
    // 用户所属号位的考核规则发生改变时所做处理
    userjudeRuleChage() {
      this.trainRules.automaticScoring[0].percentageList = [];
      this.checkedSubject.devices.forEach((item, index) => {
        if (item.rule === 2) {
          this.trainRules.automaticScoring[0].percentageList.push({
            percentage: 0.8,
            device: item.id,
          });
        }
      });
    },
    subjectChange(e) {
      this.checkedSubject = this.subjectList.find((item) => item.id === +e);
      if (+this.anewSubjectId === e) {
        this.form.id = this.$route.query.anewId;
        const group = {};
        this.checkedSubject.devices = [];
        this.form.settings.forEach((item) => {
          if (item.group === 1) {
            this.checkedSubject.devices.push(item);
          }
          if (group[item.group]) {
            group[item.group].push(item);
          } else {
            group[item.group] = [item];
          }
        });
        this.groupInfo = Object.values(group);
        this.$nextTick(() => {
          this.userjudeRuleChage();
        });
      } else {
        this.form.id = undefined;
        // this.anewSubjectId = null;
        this.groupInfo = [this.checkedSubject.devices];
      }
      console.log(this.groupInfo);
      this.trainRules.automaticScoring[0].percentageList = [];
      this.checkedSubject.devices.forEach((item) => {
        if (item.rule === 2) {
          return { percentage: 0.8, device: item.id };
        }
      });
      this.form.maxGroups =
        Math.min(...this.checkedSubject.devices.map((item) => item.groups)) ||
        0;
    },
    changeDuration(status) {
      this.form.duration = status;
    },
    async submit() {
      if (this.checkformData()) {
        const form = JSON.parse(JSON.stringify(this.form));

        delete form.settings;
        form.status = 0;
        if (form.id) {
          form.id = undefined;
          form.status = undefined;
          form.setting = this.groupInfo.map((group, i) =>
            group.map((device) => {
              return {
                group: i + 1,
                device: device.deviceInfo?.id,
                rule: device?.rule,
                user: device?.user,
              };
            })
          );
        } else {
          form.setting = this.groupInfo.map((group, i) =>
            group.map((device) => {
              return {
                group: i + 1,
                device: device?.id,
                rule: device?.rule,
                user: device?.user,
              };
            })
          );
        }

        form.duration = form.duration ? form.durationNumber : form.duration;
        form.rule = JSON.stringify(this.trainRules);
        const { data } = await createTrainApi(form);
        this.$router.push({
          path: "/train/training",
          query: { id: data.id, step: 2 },
        });
        location.reload();
      }
    },
    checkformData() {
      const errList = [];
      const form = this.form;
      if (!form.name) {
        errList.push("训练名称");
      }
      if (!form.type) {
        errList.push("训练类型");
      }
      if (!form.subject) {
        errList.push("训练科目");
      }
      if (this.$route.query.anewId) {
        this.form.settings.forEach((device, i) => {
          if (!device.user || !device.rule) {
            errList.push(`${i + 1}组【${device.name}】设备`);
          }
        });
        if (form.duration && !form.durationNumber) {
          errList.push("训练时间");
        }
        if (errList.length > 0) {
          this.$notify.error({
            title: "训练信息填写有误，请核对后再提交！",
            dangerouslyUseHTMLString: true,
            message: `<h4>以下信息有误</h4>${errList.join("、<br>")}`,
          });
          return false;
        }
      } else {
        this.groupInfo.forEach((group, i) => {
          group.forEach((device, index) => {
            if (!device.user || !device.rule) {
              errList.push(`${i + 1}组【${device.name}】设备`);
            }
          });
        });
        if (form.duration && !form.durationNumber) {
          errList.push("训练时间");
        }
        if (errList.length > 0) {
          this.$notify.error({
            title: "训练信息填写有误，请核对后再提交！",
            dangerouslyUseHTMLString: true,
            message: `<h4>以下信息有误</h4>${errList.join("、<br>")}`,
          });
          return false;
        }
      }
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.create-train {
  flex: 1;
  overflow-y: auto;
  padding-right: 0;
  position: relative;
  .v-title {
    margin: 30px 0 24px 0;
  }
  .selft-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
  }
  .selft-form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  ::v-deep .el-input__inner {
    padding-right: 50px;
  }
  .selft-form-item-height {
    display: flex;
    align-items: flex-start;
    ::v-deep .el-textarea__inner {
      height: 100%;
    }
    .form-item-label {
      margin-top: 10px;
    }
  }
  .form-item-content {
    width: 100%;
  }
  .form-item-label {
    // min-width: 80px;
    // max-width: 80px;
    font-size: 13px;
    font-weight: bold;
    white-space: nowrap;
    text-align: left;
    margin-right: 10px;
  }
  .page-floor {
    position: sticky;
    bottom: 0;
    width: 100%;
    background-color: white;
    height: 50px;
    z-index: 10;
    text-align: center;
  }
}
</style>
