<template>
  <Modal
    class="modify-grading-user"
    v-model="modalIsShow"
    :title="title"
    width="540"
    :mask-closable="false"
    @on-visible-change="visibleChange"
  >
    <Form
      ref="modalFormComp"
      class="modal-form"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      :label-width="80"
    >
      <FormItem prop="loginName" label="账号">
        <Input
          size="large"
          v-model.trim="modalForm.loginName"
          placeholder="请输入账号"
          :disabled="isEdit"
          clearable
        >
          <span slot="prepend" v-if="!isEdit">{{ loginNamePrepend }}</span>
        </Input>
      </FormItem>
      <FormItem prop="password" label="密码">
        <Input
          size="large"
          v-model.trim="modalForm.password"
          placeholder="请输入密码"
          disabled
        ></Input>
      </FormItem>
      <FormItem prop="name" label="姓名">
        <Input
          size="large"
          v-model.trim="modalForm.name"
          placeholder="请输入姓名"
          :disabled="isEdit"
          clearable
        ></Input>
      </FormItem>
      <FormItem prop="role" label="角色">
        <Select
          size="large"
          v-model="modalForm.role"
          :disabled="isEdit"
          placeholder="请选择角色"
        >
          <Option
            v-for="item in roleTypes"
            :key="item.key"
            :value="item.key"
            :label="item.val"
          ></Option>
        </Select>
      </FormItem>
      <FormItem
        prop="markRight"
        label="权限"
        v-if="modalForm.role === 'MARKER'"
      >
        <Select
          size="large"
          v-model="modalForm.markRight"
          placeholder="请选择权限"
          disabled
        >
          <Option
            v-for="(val, key) in MARKER_RIGHT_TYPE"
            :key="key"
            :value="key"
            :label="val"
          ></Option>
        </Select>
      </FormItem>
      <FormItem
        prop="weight"
        label="权重"
        v-if="
          modalForm.role === 'MARKER' &&
            modalForm.markRight &&
            modalForm.markRight !== 'ALLOW_SCORING'
        "
      >
        <InputNumber
          size="large"
          v-model.trim="modalForm.weight"
          :min="1"
          :max="100"
          :precision="2"
          placeholder="请输入权重"
          style="width: 120px"
        ></InputNumber>
      </FormItem>
      <FormItem v-if="modalForm.role === 'MARK_LEADER'">
        <Checkbox v-model="modalForm.oneClickLevel">是否一键定档</Checkbox
        ><br />
        <Checkbox v-model="modalForm.standardVolume">是否设立标准卷</Checkbox
        ><br />
        <Checkbox v-model="modalForm.levelCallback"
          >是否建议档位打回档</Checkbox
        >
      </FormItem>
    </Form>
    <div slot="footer">
      <Button shape="circle" type="primary" :disabled="isSubmit" @click="submit"
        >保存</Button
      >
      <Button shape="circle" @click="cancel">取消</Button>
    </div>
  </Modal>
</template>

<script>
import { updateGradingUser, orgDetail } from "@/api";
import { commonCode, password, numberValidator } from "@/plugins/formRules";
import { ROLE_TYPE, MARKER_RIGHT_TYPE } from "@/constants/enumerate";

const initModalForm = {
  id: "",
  workId: "",
  subject: "",
  loginName: "",
  password: "123456",
  name: "",
  role: null,
  markRight: "ALLOW_ALL",
  weight: null,
  oneClickLevel: false,
  standardVolume: false,
  levelCallback: false
};

export default {
  name: "modify-grading-user",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    subject: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "账号";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      roleTypes: [],
      MARKER_RIGHT_TYPE,
      modalForm: { ...initModalForm },
      loginNamePrepend: "",
      orgInfo: {},
      rules: {
        loginName: commonCode({ prop: "账号" }),
        password,
        name: [
          {
            required: true,
            min: 2,
            max: 20,
            message: "请输入姓名，长度2-20个字符",
            trigger: "change"
          }
        ],
        role: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change"
          }
        ],
        markRight: [
          {
            required: true,
            message: "请选择权限",
            trigger: "change"
          }
        ],
        weight: numberValidator("请输入权重")
      }
    };
  },
  created() {
    this.getOrgDetail();
  },
  methods: {
    initData(val) {
      this.$refs.modalFormComp.resetFields();
      this.roleTypes = Object.keys(ROLE_TYPE).map(key => {
        return {
          key,
          val: ROLE_TYPE[key]
        };
      });
      if (!this.isEdit) {
        this.roleTypes.filter(
          item => this.subject.stage === "INIT" || item.key === "MARK_LEADER"
        );
      }
      this.modalForm = this.$objAssign(initModalForm, val);
      this.loginNamePrepend = `${this.orgInfo.abbreviation.toLowerCase()}-${
        this.modalForm.workId
      }-`;
    },
    visibleChange(visible) {
      if (visible) {
        this.initData(this.instance);
      }
    },
    async getOrgDetail() {
      const organizationId = this.$ls.get("organizationId");
      this.orgInfo = await orgDetail(organizationId);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let result = true;
      const datas = { ...this.modalForm };
      if (!this.isEdit)
        datas.loginName = `${this.loginNamePrepend}${datas.loginName}`;
      await updateGradingUser(datas).catch(() => {
        result = false;
      });
      this.isSubmit = false;

      if (!result) return;

      this.$Message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
