import { defineComponent, watch, ref, unref } from "vue";
import { useForm } from "/@/hooks/useForm";

import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElSelect,
  type FormRules
} from "element-plus";

const rules: FormRules = {
  status: [
    {
      trigger: "blur",
      message: "请选择审批结果",
      required: true
    }
  ],
  remark: [
    {
      trigger: "blur",
      message: "请输入备注",
      required: true
    }
  ]
};

const NoramlExamineNode = defineComponent({
  name: "NoramlExamineNode",
  props: {
    rejectValue: {
      type: String,
      default: "0"
    },
    approvalValue: {
      type: String,
      default: "1"
    },
    readonly: {
      type: Boolean
    }
  },
  emits: ["examine"],
  setup(props, { emit }) {
    const rulesRef = ref({ ...rules });
    const { formRef, formData } = useForm({
      status: "",
      remark: ""
    });

    function handleExamine() {
      formRef.value.validate(isValid => {
        if (!isValid) {
          return;
        }
        emit("examine", unref(formData));
      });
    }

    watch(
      () => formData.value,
      ({ status }) => {
        const isRequired = status === "0";
        rulesRef.value.remark[0].required = isRequired;
      },
      {
        immediate: true,
        deep: true
      }
    );

    return () => {
      const { approvalValue, rejectValue } = props;

      return (
        <ElForm
          ref={formRef}
          model={formData.value}
          rules={rulesRef.value}
          labelWidth="100px"
          style="width:100%"
        >
          <ElFormItem prop="status" label="审核状态">
            <div class="flex justify-between w-full">
              <ElSelect
                v-model={formData.value.status}
                placeholder="请选择审批结果"
              >
                <ElOption value={approvalValue} label="通过" />
                <ElOption value={rejectValue} label="驳回" />
              </ElSelect>

              <ElButton type="primary" onClick={handleExamine}>
                保存
              </ElButton>
            </div>
          </ElFormItem>

          <ElFormItem prop="remark" label="审核备注">
            <ElInput
              v-model={formData.value.remark}
              placeholder="请输入备注"
              maxlength="250"
              type="textarea"
            />
          </ElFormItem>
        </ElForm>
      );
    };
  }
});

export default NoramlExamineNode;
