<script>
import { listCommondepartment } from "@/api/common";
import { save, show, store, index, destroy } from "@/api/person";
import { CreateDialog } from "@/utils/createDialog"
import { deepCopy } from "@/utils";
export default {
  props: {
    tableName: String,
  },
  render(h) {
    let dialog = new CreateDialog(this,[
    ],{
      width: "570px"
    })
    return dialog.render()
  },
  data() {
    return {
      columns: 1,
      row: {},
      formInfo: [
        {
          name: "部门",
          field: "department_id",
          edit_input: "radio",
          form_show: true,
          _params: []
        },
        {
          name: "人员类型",
          field: "person_type",
          edit_input: "radio",
          form_show: true,
          _params: []
        },
        {
          name: '姓名',
          field: 'name',
          edit_input: 'text',
          form_show: true
        },
        // {
        //   name: '职位',
        //   field: 'position',
        //   edit_input: 'text',
        //   form_show: true
        // },
        // {
        //   name: '是否在职',
        //   field: 'is_active',
        //   edit_input: 'el-switch',
        //   form_show: true,
        //   _props: {
        //     "active-text": "是",
        //     "inactive-text": "否",
        //     "active-value": 1,
        //     "inactive-value": 0,
        //   }
        // },
        {
          name: '用户名',
          field: 'username',
          edit_input: 'text',
          form_show: true
        },
        {
          name: '密码',
          field: 'password',
          edit_input: 'text',
          form_show: true,
          _props: {
            type: "password"
          }
        },
        {
          name: '开始填报日期',
          field: 'start_date',
          edit_input: 'date',
          form_show: true
        },
        {
          name: '结束填报日期',
          field: 'end_date',
          edit_input: 'date',
          form_show: true
        },
        {
          name: '',
          field: '',
          edit_input: 'placeholdertext',
          placeholdertext:'留空表示填报状态持续开启，不留空系统会自动刷新填报状态',
          form_show: true,
        }
      ],
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {
        name: [
          { required: true,message: "请填写姓名" }
        ],
        // position: [
        //   { required: true,message: "请填写职位" }
        // ],
        // is_active: [
        //   { required: true,message: "请选择是否在职" }
        // ],
        department_id: [
          { required: true,message: "请选择部门" }
        ],
        username: [
          { required: true,message: "请填写用户名" }
        ],
        password: [
          {
            validator:(rule,value,cb) => {
              if (!value) {
                cb();
                return
              }
              /^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/.test(value) ? cb() : cb(new Error("至少1个大写字母，1个小写字母，1个数字，1个特殊字符"))
            }
          }
        ]
      },
      file: {},
    };
  },
  methods: {
    setRow (row) {
      this.row = row
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["elForm"].clearValidate();
    },
    show() {
      this.dialogVisible = true;
    },
    hidden() {
      this.dialogVisible = false;
    },
    setType(type = "add") {
      let types = ["add", "editor", "show"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type + "type:add or editor or show");
      }
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },

    async getDetail() {
      const res = await show({ id: this.id });
      this.$integrateData(this.form, res);

      this.formInfo.forEach((i) => {
        if (i && (i.edit_input === "file" || i.edit_input === "files")) {
          res[i._relations.link_with_name]
            ? (this.file[i.field] =
              res[i._relations.link_with_name] instanceof Array
                ? res[i._relations.link_with_name].map((i) => {
                  return {
                    name: i?.name,
                    url: i?.url,
                    response: i,
                  };
                })
                : [
                  {
                    name: res[i._relations.link_with_name]?.name,
                    url: res[i._relations.link_with_name]?.url,
                    response: res[i._relations.link_with_name],
                  },
                ])
            : (this.file[i.field] = []);
        }

        this.form = Object.assign({}, this.form);
        this.originalForm = deepCopy(res);
      });
    },

    submit() {
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
        store(this.form).then(res => {
          this.$Message.success({
            content: `${this.type === "add" ? "新增" : "编辑"}成功`,
          });
          this.$emit("refresh");
          this.hidden();
        })
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
        save(this.form).then(res => {
          this.$Message.success({
            content: `${this.type === "add" ? "新增" : "编辑"}成功`,
          });
          this.$emit("refresh");
          this.hidden();
        })
      }
    },
  },
  computed: {
    title () {
      if (this.type === 'add') return '新增'
      if (this.type === 'editor') return '编辑'
      if (this.type === 'show') return '查看'
    }
  },
  watch: {
    formInfo: {
      handler: function (newVal) {
        this.form = {};
        this.file = {};
        newVal.forEach((i) => {
          if (i.field) {
            this.form[i.field] = "";
            if (
              i.validation instanceof Array &&
              i.validation.length > 0 &&
              !!i.validation.find((i) => i === "required")
            ) {
            }
            if (i.edit_input === "files") {
              this.form[i.field] = [];
            }
            if (i.edit_input === "files" || i.edit_input === "file") {
              this.file[i.field] = [];
            }
            if (i.edit_input === "checkbox") {
              this.form[i.field] = [];
            }
            if (i._relations) {
              this.form[i._relations?.link_with_name] = [];
            }
          }
        });

        this.columns = newVal.length > 11 ? '2' : '1'
      },
      immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        document.documentElement.style.setProperty(
          "--column-num",
          this.columns
        );
        if (this.type === "editor" || this.type === "show") {
          this.$nextTick(() => this.getDetail());
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        delete this.form.id;
        for (let key in this.file) {
          this.file[key] = [];
        }
      }
    },
  },
  created() {
    listCommondepartment().then(res => {
      this.formInfo.find(i => i.field === 'department_id')._params = res.data
    })
  }
};
</script>

<style>
:root {
  --column-num: 2;
}
</style>
<style scoped lang="scss">
.uploaded-a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

.uploaded-a:hover {
  color: red;
  text-decoration: underline;
}

.form-body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(var(--column-num), 1fr);
}

::v-deep .el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}
</style>
