<template>
  <div class="v-page operation-setting">
    <h2 class="v-title">基本信息设置</h2>
    <el-form inline :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="科目名称" prop="name">
        <el-input
          style="width: 300px; min-width: 100px"
          placeholder="请输入科目名称"
          v-model="form.name"
          maxlength="30"
          class="custom-input"
          show-word-limit
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="科目类型" prop="train">
        <el-cascader
          ref="subjectTypeCascader"
          style="width: 300px; min-width: 100px"
          :props="{ emitPath: false, value: 'id', label: 'name' }"
          v-model="form.train"
          @change="getClassifyList"
          :options="subjectTypeList"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="科目分类" prop="classify">
        <el-cascader
          style="width: 300px; min-width: 100px"
          :options="classifyList"
          v-model="form.classify"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children,
            emitPath: false,
          }"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="科目说明" class="form-item-100">
        <el-input
          placeholder="请输入科目介绍"
          class="comment-textarea"
          style="width: 100%; min-width: 300px"
          type="textarea"
          maxlength="200"
          show-word-limit
          v-model="form.comment"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="操作设备" class="form-item-100" prop="checkedDevice">
        <el-select
          style="width: 30%; min-width: 300px"
          v-model="checkedDevice"
          @change="getDeviceInfo"
          multiple
          placeholder="请选择需要的操作设备"
        >
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作规程" prop="age">
        <span v-if="form.pdf">
          <a target="_blank" :href="form.pdf.fileLinkTransfer()"
            >{{ typeof form.pdf === "string" ? form.pdf : form.pdf.name }}
          </a>
          <el-tooltip
            class="item"
            effect="dark"
            content="刪除规程"
            placement="top"
          >
            <i class="el-icon-delete del-icon" @click="form.pdf = null"></i>
          </el-tooltip>
        </span>
        <el-button
          v-if="!form.pdf"
          @click="uploadrRuleFile"
          icon="el-icon-plus"
          class="upload-button"
          >上传操作规程</el-button
        >
      </el-form-item>
    </el-form>
    <h2 class="v-title">添加操作步骤</h2>
    <TableSelf
      :data="form.step"
      :column="column"
      height="340"
      v-loading="stepDataInitOver"
    >
      <template v-slot:operation="props">
        <el-cascader
          @change="test"
          :props="{
            value: 'keycode',
            label: 'name',
            emitPath: true,
          }"
          :options="deviceInfoList"
          v-model="props.row.checkInfo"
        >
          <template slot-scope="{ node, data }" v-if="data.operation">
            <div>
              <div>{{ data.name }}</div>
              <div style="font-size: 12px; color: #ccc; line-height: 20px">
                {{ data.comment }}
              </div>
            </div>
          </template>
        </el-cascader>
      </template>
      <template v-slot:delay="props">
        <el-input-number
          v-model="props.row.delay"
          :min="0"
          size="mini"
          label="请输入延迟用时"
        ></el-input-number>
      </template>
      <template v-slot:duration="props">
        <el-input-number
          v-model="props.row.duration"
          :min="1"
          size="mini"
          label="请输入操作用时"
        ></el-input-number>
      </template>
      <template v-slot:action="props">
        <div class="actionbar-box">
          <el-button type="text" size="mini" @click="insertTo(props, 0)">
            <i class="el-icon-upload2 actionbar-button"></i>上方插入</el-button
          >
          <el-button type="text" size="mini" @click="insertTo(props, 1)"
            ><i class="el-icon-download actionbar-button"></i
            >下方插入</el-button
          >
          <el-button
            type="text"
            size="mini"
            @click="moveItem(props, -1)"
            :disabled="props.$index === 0"
          >
            <i class="el-icon-top actionbar-button"></i>上移</el-button
          >
          <el-button
            type="text"
            size="mini"
            @click="moveItem(props, 1)"
            :disabled="props.$index === form.step.length - 1"
            ><i class="el-icon-bottom actionbar-button"></i>下移</el-button
          >
          <el-button
            type="text"
            style="color: #f56c6c"
            size="mini"
            :disabled="form.step.length === 1"
            @click="removeItem(props)"
          >
            <i class="el-icon-delete actionbar-button"></i>移除</el-button
          >
        </div>
      </template>
      <template v-slot:comment="props">
        <el-input
          v-model="props.row.comment"
          placeholder="请输入步骤说明"
          :maxlength="30"
          show-word-limit
        ></el-input>
      </template>
    </TableSelf>
    <div class="page-footer">
      <el-button type="danger" @click="onCancel">取消</el-button>
      <el-button type="primary" @click="submitForm()">保存</el-button>
    </div>
  </div>
</template>

<script>
import TableSelf from "@/components/layout/TableLayout.vue";
import {
  getSubjectDetailsApi,
  createSubjectApi,
  editorSubjectApi,
  getSubjectClassifyApi,
  getSubjectTypeApi,
} from "@/api/training/subject";
import { getDeviceApi, getDevicesInfoApi } from "@/api/training/device";
import { getDistFile } from "@/utils";
import { uploadApi } from "@/api/system";

export default {
  components: {
    TableSelf,
  },
  data() {
    return {
      // 编辑的科目表单
      form: {},
      stepDataInitOver: false,
      // 表单的规则
      rules: {
        name: [{ required: true, message: "请输入科目名称", trigger: "blur" }],
        checkedDevice: [
          {
            message: "请选择操作设备",
            trigger: "change",
            validator: (r, v, c) => {
              return !this.checkedDevice || this.checkedDevice.length < 1
                ? c(new Error("请选择操作设备"))
                : c();
            },
          },
        ],
        train: [{ required: true, message: "请选择科目类型", trigger: "blur" }],
        classify: [
          { required: true, message: "请选择科目分类", trigger: "blur" },
        ],
      },
      classifyList: [],
      subjectTypeList: [],
      // 步骤信息
      tableData: [],
      // 所有设备列表
      deviceList: [],
      // 所有设备详细信息列表
      deviceInfoList: [],
      // 选择的设备
      checkedDevice: [],
      column: [
        {
          type: "index",
          label: "序号",
          width: 50,
          align: "center",
          "show-overflow-tooltip": true,
        },
        {
          prop: "operation",
          label: "操作内容(操作设备-操作按键-按键状态)",
          align: "center",
          width: 350,
          "show-overflow-tooltip": true,
        },
        {
          prop: "delay",
          label: "延迟用时/秒",
          width: 200,
          align: "center",
          "show-overflow-tooltip": true,
        },
        {
          prop: "duration",
          label: "操作用时/秒",
          width: 200,
          align: "center",
          "show-overflow-tooltip": true,
        },
        {
          prop: "action",
          label: "操作维护",
          width: 500,
          align: "center",
          "show-overflow-tooltip": true,
        },
        {
          prop: "comment",
          label: "步骤说明",
          align: "center",
          "show-overflow-tooltip": true,
        },
      ],
    };
  },
  mounted() {
    this.$refs.form?.clearValidate();
  },
  activated() {
    this.init();
  },
  methods: {
    async init() {
      this.stepDataInitOver = true;
      const id = this.$route.query.id;
      // 获取设备列表
      const { data } = await getDeviceApi();
      // 获取训练类型
      this.getSubjectType();
      this.deviceList = data;
      if (id) {
        const { data } = await getSubjectDetailsApi(id);
        this.checkedDevice = [];
        data.step.forEach((item) => {
          item.checkInfo = [item.device, item.part, item.operation];
        });
        data.device.forEach((item) => {
          this.checkedDevice.push(item.id);
        });
        this.$set(this, "form", data);
        this.form = data;
          setTimeout(() => {
            this.stepDataInitOver = false;
          }, 0);
      } else {
        this.$set(this, "form", { step: [{ duration: 1 }], device: undefined });
        this.stepDataInitOver = false;
        this.checkedDevice = [];
      }
      this.$nextTick(() => {
        this.$refs.form?.clearValidate();
      });
      this.getClassifyList();
      this.getDeviceInfo();
    },
    // 获取科目类型信息
    async getSubjectType() {
      const { data } = await getSubjectTypeApi();
      this.subjectTypeMap = data.toTree();
      this.subjectTypeList = this.subjectTypeMap.tree;
    },
    // 获取科目分类列表
    async getClassifyList() {
      if (this.form.train) {
        const { data } = await getSubjectClassifyApi({ id: this.form.train });
        if (!data.map((item) => item.train).includes(this.form.train)) {
          this.form.classify = null;
        }
        this.classifyList = data;
      }
      const { data } = await getSubjectClassifyApi({ id: this.form.train });
      this.subjectClassifyMap = data.toTree();
      this.classifyList = this.subjectClassifyMap.tree;
    },
    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (isok) => {
        if (!isok) return;
        const errList = [];
        this.form.step.forEach((item, index) => {
          item.sort = index + 1;
          if (!item.checkInfo || item.checkInfo.length === 0) {
            errList.push(index + 1);
          } else {
            item.device = item.checkInfo[0];
            item.part = item.checkInfo[1];
            item.operation = item.checkInfo[2];
          }
        });
        // 如果步骤信息存在问题
        if (errList.length) {
          this.$message.error(
            `当前第${errList.join("、")}步骤设备信息存在错误，请重新编辑！`
          );
          return;
        }
        this.form.device = this.checkedDevice;
        if (this.form.pdf instanceof File) {
          const { data } = await uploadApi(this.form.pdf, {
            data: { type: "rulespdf" },
          });
          this.form.pdf = data.diskname;
        }
        if (this.form.id) {
          await editorSubjectApi(this.form.id, this.form);
        } else {
          await createSubjectApi(this.form);
        }
        this.$router.push("/train/subject");
        console.log(this.form);
      });
    },
    async getDeviceInfo() {
      if (this.checkedDevice.length > 0) {
        const { data } = await getDevicesInfoApi(this.checkedDevice);
        // 将deviceinfo处理成标准的children树
        data?.forEach((device) => {
          device.keycode = device.id;
          device.children = device.part || [];
          device.children.forEach((part) => {
            part.children = part.operation || [];
          });
        });
        this.formartStepList(data);
        this.deviceInfoList = data;
      } else {
        this.formartStepList([]);
        this.deviceInfoList = [];
      }
    },
    /**
     * 判断当前科目的步骤是否存在未选中的操作设备
     * 若步骤中存在未选中的操作设备则清空该步骤 并存储至prevCheckInfo以在用户重新选中时恢复该设备相关步骤，
     * 防止用户出现错误操作
     */
    formartStepList(data) {
      const devInfoIdList = data.map((x) => x.id);
      this.form.step.forEach((item) => {
        if (
          item.prevCheckInfo &&
          devInfoIdList.includes(item.prevCheckInfo[0])
        ) {
          item.checkInfo = item.prevCheckInfo;
          item.prevCheckInfo = [];
        }
        // 不存在则清空备份
        if (item.checkInfo && !devInfoIdList.includes(item.checkInfo[0])) {
          item.prevCheckInfo = item.checkInfo;
          item.checkInfo = [];
        }
      });
    },
    async onCancel() {
      await this.$confirm("确定退出吗？当前所有编辑将不保存！", "提示", {
        type: "warning",
      });
      this.$router.push("/train/subject");
    },
    // 上方或下方插入
    /**
     * @param {props} data
     * @param {index} offset
     */
    insertTo(data, offset) {
      const index = data.$index;
      this.form.step.splice(index + offset, 0, { duration: 1 });
    },
    // 上移或下移
    /**
     * @param {props} props
     * @param {index} offset
     */
    moveItem(props, offset) {
      const nowIndex = props.$index;
      const prevIndex = Math.max(
        0,
        Math.min(nowIndex + offset, this.form.step.length - 1)
      );
      const [nowData, prevData] = [
        this.form.step[nowIndex],
        this.form.step[prevIndex],
      ];

      this.form.step.splice(nowIndex, 1, prevData);
      this.form.step.splice(prevIndex, 1, nowData);

      // this.form.step[props.$index] = prevData
      // this.form.step[props.$index - 1 < 0 ? 0 : props.$index - 1] = nowData
      // console.log(this.form.step)
      // this.$forceUpdate()
    },
    removeItem({ $index }) {
      if (this.form.step.length === 1) {
        this.$message.warning("必须保留1个步骤");
        return;
      }
      this.form.step.splice($index, 1);
    },

    sortStep() {},
    selectDevice() {},
    async uploadrRuleFile() {
      const [file] = await getDistFile({ accepts: ["pdf"] });
      this.form.pdf = file;
    },
  },
};
</script>
<style  lang="scss" scope>
.custom-input {
  input {
    padding-right: 30px;
  }
  .el-input__suffix {
    background-color: white;
    height: calc(100% - 2px);
    right: 3px;
    top: 1px;
  }
}
</style>
<style lang="scss" scoped>
.v-page {
  display: unset;
  margin-bottom: 10px;
}

.v-title {
  margin-bottom: 20px;
}
.upload-button {
  border-style: dashed;
  border-color: #38b0be;
  color: #38b0be;
  font-weight: bold;
}
::v-deep .comment-textarea {
  textarea {
    height: 100px;
    max-height: 100px;
  }
}
.page-footer {
  padding: 20px 0;
  width: 100%;
  display: flex;
  justify-content: center;
}
.del-icon {
  color: #f56c6c;
  cursor: pointer;
  font-weight: bold;
}
.actionbar-box {
  width: 100%;
  font-size: 15px;
}
.actionbar-button {
  font-weight: bold;
}
.is-disabled {
  color: #c0c4cc !important;
}
::v-deep .form-item-100 {
  width: 100%;
  .el-form-item__content {
    width: calc(100% - 100px);
  }
}
</style>
