<template>
  <lrlayout>
    <div :class="prefixCls">
      <div :class="`${prefixCls}_content`">
        <a-form
          ref="formModuleRef"
          :rules="rules"
          :model="formData"
          labelAlign="right"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item label="编号" name="code">
            <a-input v-model:value="formData.code" />
          </a-form-item>
          <a-form-item label="名称" name="name">
            <a-input v-model:value="formData.name" />
          </a-form-item>
          <a-form-item label="图标" name="icon">
            <IconPicker v-model:value="formData.icon" />
          </a-form-item>
          <a-form-item label="表单选择" name="formCodeName" @click="handleShow">
            <a-input v-model:value="formData.formCodeName">
              <template #addonAfter>
                <FileTextOutlined />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item label="表单选择" name="formCode" v-show="false">
            <a-input v-model:value="formData.formCode" />
          </a-form-item>
          <a-form-item label="表单版本" name="formVerison">
            <a-select v-model:value="formData.formVerison" :options="formVerisons" />
          </a-form-item>
          <a-form-item label="上级" name="pmoduleId">
            <a-tree-select
              v-model:value="formData.pmoduleId"
              :tree-data="pmoduleIds"
              :field-names="{ label: 'name', value: 'id' }"
            />
          </a-form-item>
          <a-form-item label="状态" name="enabledMark">
            <a-radio-group v-model:value="formData.enabledMark" size="mini" button-style="solid">
              <a-radio-button :value="1">是</a-radio-button>
              <a-radio-button :value="0">否</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <!-- <a-form-item label="是否系统" name="isSys">
            <a-radio-group v-model:value="formData.isSys" size="mini" button-style="solid">
              <a-radio-button :value="true">是</a-radio-button>
              <a-radio-button :value="false">否</a-radio-button>
            </a-radio-group>
          </a-form-item> -->
          <a-form-item label="排序" name="sortCode">
            <a-input-number v-model:value="formData.sortCode" :min="0" />
          </a-form-item>
          <a-form-item label="描述" name="description">
            <a-textarea v-model:value="formData.description" />
          </a-form-item>
        </a-form>
        <div :class="`${prefixCls}_formLine`"></div>
      </div>
    </div>
    <ModuleModal @register="registerModal" @get-scheme-row="getSchemeRow" />
  </lrlayout>
</template>

<script lang="ts" setup>
  import { FileTextOutlined } from '@ant-design/icons-vue';
  import { defineEmits, ref, onMounted, watch, defineExpose } from 'vue';
  import { IconPicker } from '@/components/Icon';
  import { TreeItem } from '@/components/Tree';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getMenuList } from '@/api/demo/system';
  import { useI18n } from '@/hooks/web/useI18n';
  import { FormInstance } from 'ant-design-vue';
  import ModuleModal from './modalForm-Modal.vue';
  import { functionGetSchemePageList, functionGetForm } from '@/api/demo/formScheme';
  import { Get_Get_ExistFiled } from '@/api/demo/formModule';

  // emit
  const emit = defineEmits(['change-form-verisons', 'set-steps-current']);
  // message
  const { createMessage } = useMessage();
  // useI18n
  const { t } = useI18n();
  // 定义props
  const props = defineProps({
    editData: {
      type: Object,
      default: () => ({}),
    },
    isNextSteps: {
      type: Boolean,
      default: () => false,
    },
    isEdit: {
      type: Boolean,
      default: () => false,
    },
    formVerison_now: {
      type: String,
      default: () => '',
    },
  });
  // 表单栅格
  const labelCol = { span: 4 };
  const wrapperCol = { span: 20 };

  // 表单选择声明
  const [registerModal, { openModal }] = useModal();
  // 表单ref
  // let formModuleRef: FormInstance | null = null;
  const formModuleRef = ref()
  // 版本options
  const formVerisons = ref([]);
  // 上级options
  const pmoduleIds: any = ref<TreeItem[]>([]);

  // 参数
  const formData = ref({
    type: 1,
    code: '',
    name: '',
    icon: 'ant-design:star-outlined',
    formCode: '',
    formCodeName: '',
    formVerison: '',
    pmoduleId: '',
    moduleId: '',
    enabledMark: 1,
    isSys: true,
    sortCode: '0',
    description: '',
  });
  // 规则
  let rules = {
    code: [
      {
        required: true,
        asyncValidator: async (rule, value, callback) => {
          // 验证逻辑
          if (value) {
            // 判断数据表字段重复
            try {
              let filedsJson = {
                Code: formData.value.code,
              };
              if (props.isEdit) {
                // 编辑
                let query: any = {
                  keyValue: props.editData.record.id,
                  tableName: 'form_module',
                  keyName: 'Id',
                  filedsJson: JSON.stringify(filedsJson),
                };
                await Get_Get_ExistFiled(query).then((res) => {
                  if (res) {
                    callback();
                  } else {
                    callback(new Error('编号重复'));
                  }
                });
              } else {
                // 新增
                let query: any = {
                  tableName: 'form_module',
                  keyName: 'Id',
                  filedsJson: JSON.stringify(filedsJson),
                };
                await Get_Get_ExistFiled(query).then((res) => {
                  if (res) {
                    callback();
                  } else {
                    callback(new Error('编号重复'));
                  }
                });
              }
            } catch (error) {
              if (error) {
                emit('set-steps-current', false);
              }
            }
          } else {
            callback(new Error('请输入编号'));
          }
        },
        trigger: 'blur',
      },
    ],
    name: [
      {
        required: true,
        message: '请输入名称',
        trigger: 'blur',
      },
    ],
    icon: [
      {
        component: 'IconPicker',
        required: true,
        message: '请选择图标',
        trigger: 'blur',
      },
    ],
    formCodeName: [
      {
        required: true,
        message: '请选择表单版本',
        trigger: 'blur',
      },
    ],
    formVerison: [
      {
        required: true,
        message: '请选择表单版本',
        trigger: 'blur',
      },
    ],
    pmoduleId: [
      {
        required: true,
        message: '请选择上级',
        trigger: 'blur',
      },
    ],
    enabledMark: [{ required: true }],
  };

  // 监视props
  watch(
    () => props.editData,
    () => {
      if (props.isEdit) {
        // 编辑
        setFormData(props.editData.record);
      } else {
        // 新增
        formData.value = props.editData.record;
      }
    },
  );

  // 监视props
  watch(
    () => props.isNextSteps,
    async () => {
      console.log('props.isNextSteps',props.isNextSteps)
      if (props.isNextSteps) {
        // 判断数据表字段重复
        console.log('formModuleRef.value',formModuleRef,formModuleRef.value)
        if (formModuleRef.value) {
          try {
            const valid = await formModuleRef.value.validate();
            if (valid.errorFields) {
              emit('set-steps-current', false);
            } else {
              emit('set-steps-current', true);
            }
          } catch (error) {
            if (error) {
              emit('set-steps-current', false);
            }
          }
        }
      }
    },
  );
  // 监视formVerison
  watch(
    () => formData.value.formVerison,
    () => {
      if (formData.value.formVerison) {
        changevalidateSteps();
      }
    },
  );

  // 表单选择打开
  function handleShow() {
    openModal();
  }
  // 表单选择回传数据-版本
  async function getSchemeRow(row) {
    let formVerisons_temp: any = [];
    formData.value.formCode = row.id;
    formData.value.formCodeName = row.name;
    // 表单选择回传数据变化后，版本变化
    let query: any = { schemeInfoId: row.id };
    const historyData = await functionGetSchemePageList(query);
    historyData.items.forEach((t) => {
      formVerisons_temp.push({ label: t.createDate, value: t.id });
    });
    formVerisons.value = formVerisons_temp;

    // 编辑-按照旧的版本
    if (props.isEdit) {
      formData.value.formVerison = formVerisons_temp.find((t) => {
        return t.value === props.formVerison_now;
      });
    } else {
      // 新增-默认最新的版本
      formData.value.formVerison = formVerisons_temp[0].value;
    }
  }

  // 版本改变后传输数据给父组件
  function changevalidateSteps() {
    emit('change-form-verisons', formData.value.formVerison);
  }

  // 上级
  async function fetch() {
    pmoduleIds.value = await getMenuList();
    pmoduleIds.value.unshift({ id: '0', name: '根节点' });
  }

  // 编辑时的初始值
  async function setFormData(record) {
    // info和scheme
    let query: any = { id: record.formCode };
    const result: any = await functionGetForm(query);
    record.isSys = true;
    formData.value = record;
    formData.value.formVerison = props.formVerison_now;
    getSchemeRow(result.info);
  }

  defineExpose({
    formData,
  });
  onMounted(() => {
    fetch();
  });

  const prefixCls = 'l-rblock';
</script>

<style lang="less" scoped>
  .l-rblock {
    width: 100%;
    height: 100%;
    background-color: @border-color-base;

    &_content {
      box-sizing: border-box;
      position: relative;
      width: 100%;
      height: 100%;
      max-width: 794px;
      overflow: hidden auto;
      background: @component-background;
      border-radius: 4px;
      margin: auto;
      padding: 24px;
    }

    &_formLine {
      height: 50px;
    }
  }
</style>
