<template>
  <div class="client-param-set">
    <Row :gutter="20" type="flex">
      <Col span="12">
        <div class="part-box">
          <h2 class="client-param-title">科目名称设置</h2>
          <table class="table table-noborder">
            <template v-for="(subject, index) in subjects">
              <tr :key="index">
                <td>
                  <Input
                    v-model="subject.name"
                    @on-blur="checkSubjectValidate(subject)"
                    :disabled="!subject.enable"
                    :readonly="!subject.canEdit"
                    :clearable="subject.canEdit"
                    :ref="subject.id"
                  ></Input>
                </td>
                <td style="width: 220px;">
                  <Button
                    size="small"
                    :disabled="!subject.enable"
                    @click="toEdit(index)"
                    >编辑</Button
                  >
                  <Button
                    size="small"
                    :type="subject.enable ? 'error' : 'success'"
                    @click="toAble(index)"
                  >
                    {{ subject.enable ? "禁用" : "启用" }}</Button
                  >
                  <Button
                    size="small"
                    :disabled="!subject.enable"
                    @click="toSave(subject)"
                    >保存</Button
                  >
                </td>
              </tr>
              <tr
                class="tr-tips-error"
                v-if="subject.errors"
                :key="index + '1'"
              >
                <td>{{ subject.errors.name }}</td>
                <td></td>
              </tr>
            </template>
          </table>
        </div>
      </Col>
      <Col span="12">
        <div class="part-box">
          <h2 class="client-param-title">其他设置</h2>
          <Form ref="modalFormComp" :model="modalForm" :label-width="120">
            <!-- <FormItem label="是否整包扫描：">
              <Select
                v-model="modalForm.packageScan"
                :disabled="!modalFormCanEdit"
                placeholder="是否整包扫描"
              >
                <Option
                  v-for="(val, key) in BOOLEAN_TYPE"
                  :key="key"
                  :value="key * 1"
                  :label="val"
                ></Option>
              </Select>
            </FormItem> 
            <FormItem label="图片是否加密：">
              <Select
                v-model="modalForm.imageEncrypt"
                :disabled="!modalFormCanEdit"
                placeholder="图片是否加密"
              >
                <Option
                  v-for="(val, key) in BOOLEAN_TYPE"
                  :key="key"
                  :value="key * 1"
                  :label="val"
                ></Option>
              </Select>
            </FormItem>
            <FormItem label="图片命名规则：">
              <Select
                v-model="modalForm.nameRule"
                :disabled="!modalFormCanEdit"
                placeholder="请选择图片命名规则"
              >
                <Option
                  v-for="(val, key) in IMAGE_NAME_TYPE"
                  :key="key"
                  :value="key * 1"
                  :label="val"
                ></Option>
              </Select>
            </FormItem> -->
            <FormItem label="试卷档位：">
              <Select
                v-model="modalForm.paperStage"
                :disabled="!modalFormCanEdit"
                placeholder="请选择试卷档位"
              >
                <Option
                  v-for="(val, key) in PAPER_LEVEL_KNOWN_TYPE"
                  :key="key"
                  :value="key * 1"
                  :label="val"
                ></Option>
              </Select>
            </FormItem>
            <FormItem>
              <Button
                shape="circle"
                style="width: 80px;"
                @click="modalFormCanEdit = true"
                >编辑</Button
              >
              <Button
                shape="circle"
                type="primary"
                style="width: 80px;"
                :disabled="isSubmit"
                @click="toSubmit"
                >保存</Button
              >
            </FormItem>
          </Form>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import {
  subjectList,
  updateSubject,
  enableSubject,
  getParamsSet,
  updateCollectParams
} from "@/api";
import {
  BOOLEAN_TYPE,
  IMAGE_NAME_TYPE,
  PAPER_LEVEL_KNOWN_TYPE
} from "@/constants/enumerate";
import schema from "async-validator";
schema.warning = function() {};

const initSubject = {
  id: "",
  name: "",
  enable: true,
  canEdit: false,
  password: ""
};

export default {
  name: "client-param-set",
  data() {
    return {
      BOOLEAN_TYPE,
      IMAGE_NAME_TYPE,
      PAPER_LEVEL_KNOWN_TYPE,
      workId: this.$route.params.workId,
      subjects: [],
      // other param
      isSubmit: false,
      initModalForm: {
        workId: "",
        packageScan: 0,
        imageEncrypt: 0,
        nameRule: 0,
        paperStage: 0
      },
      modalFormCanEdit: false,
      modalForm: {}
    };
  },
  mounted() {
    this.modalForm = { ...this.initModalForm };
    this.getList();
    this.getParamsSetInfo();
  },
  methods: {
    async getList() {
      const data = await subjectList(this.workId);
      this.subjects = data.map(item => {
        return {
          ...item,
          canEdit: false
        };
      });
    },

    toAdd() {
      this.subjects.push({ ...initSubject });
    },
    toEdit(index) {
      const row = this.subjects[index];
      row.canEdit = true;
      this.$refs[row.id][0].focus();
    },
    async toAble(index) {
      const row = this.subjects[index];
      await enableSubject(row.id);
      row.enable = !row.enable;
    },
    checkSubjectValidate(subject) {
      const descriptor = {
        name: [
          {
            required: true,
            min: 2,
            max: 20,
            message: "科目名称长度只能介于2到20之间"
          }
        ]
      };
      return new schema(descriptor)
        .validate(subject)
        .then(() => {
          if (subject.errors) subject.errors = null;
        })
        .catch(({ errors, fields }) => {
          let errorMsgs = {};
          errors.map(error => {
            errorMsgs[error.field] = error.message;
          });
          this.$set(subject, "errors", errorMsgs);
          return { errors };
        });
    },
    async toSave(row) {
      const result = await this.checkSubjectValidate(row);
      if (result) return;

      await updateSubject(row);
      row.canEdit = false;
      this.$Message.success("保存成功！");
    },
    // param-set
    async getParamsSetInfo() {
      const data = await getParamsSet(this.workId);
      this.modalForm = this.$objAssign(this.modalForm, data);
    },
    async toSubmit() {
      if (this.isSubmit) return;
      this.isSubmit = true;

      let result = true;
      await updateCollectParams(this.modalForm).catch(() => {
        result = false;
      });
      this.isSubmit = false;
      if (!result) return;
      this.modalFormCanEdit = false;
      this.$Message.success("保存成功！");
    }
  }
};
</script>
