<template>
  <div :class="`${prefixCls}`">
    <div :class="`${prefixCls}-header`">{{ paramsTitle }}</div>
    <div :class="`${prefixCls}-content`">
      <BasicForm ref="myDataBaseFormRef" @register="registerForm" v-if="formModalVisible" />
    </div>
    <div :class="`${prefixCls}-footer`">
      <div :class="`${prefixCls}-footer-confirm`" @click="submitClick">保存</div>
      <div :class="`${prefixCls}-footer-cancle`" @click="close">取消</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { unref, ref, onMounted } from 'vue';
  import { getFormsDesignData, getFormsDataDetail, saveFormsData } from '@/api/formrender/index';
  import { getOutKeyList } from '@/api/formdesign/index';
  import { FormSchema } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRoute } from 'vue-router';

  const emit = defineEmits(['success']);
  const route = useRoute();
  const { createMessage } = useMessage();
  const formModalVisible = ref(false);
  const isUpdate = ref(true);
  const schemeId = ref();
  const paramsKey = ref();
  const addQuery: any = ref([]);
  const formColumns: FormSchema[] = [];
  const paramsTitle = route.query.name;
  const paramsCode = route.query.code;
  const paramsKeyValue = route.query.keyValue; //keyValue编辑传新增不传
  if (paramsKeyValue) {
    isUpdate.value = true;
  } else {
    isUpdate.value = false;
  }

  function generateUniqueDigits(length: number): number[] {
    const digits = new Set<number>();
    while (digits.size < length) {
      const randomDigit = Math.floor(Math.random() * 20);
      digits.add(randomDigit);
    }
    return Array.from(digits);
  }

  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    labelAlign: 'right',
    schemas: formColumns,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });
  //取消
  function close() {}
  //表单填写数据
  async function submitClick() {
    try {
      const values = await validate();
      let query = values;
      let params: any = {
        schemeId: schemeId.value,
        isUpdate: isUpdate.value,
        pkey: paramsKey.value,
      };
      if (unref(isUpdate)) {
        params.pkeyValue = paramsKeyValue;
      } else {
        addQuery.value.forEach((item) => {
          if (item.type == 'main') {
            params.pkeyValue = item.value;
          }
          if (!query[item.field]) {
            query[item.field] = item.value;
          }
        });
      }
      params.data = JSON.stringify(query);

      const data = await saveFormsData(params);
      if (data) {
        emit('success');
        return createMessage.success('操作成功');
      } else {
        return createMessage.error('操作失败');
      }
    } finally {
      console.log('err');
    }
  }
  function getPublicForm() {
    let params = {
      code: paramsCode,
    };
    getFormsDesignData(params).then((res: Recordable) => {
      let formObj = JSON.parse(res.formScheme.scheme);
      formObj.formInfo.schemas.forEach((item) => {
        formColumns.push(item);
      });
      formModalVisible.value = true;
      schemeId.value = res.formScheme.id;
      paramsKey.value = formObj.primaryKey;
      let arr: any = [];
      formObj.db.forEach((val) => {
        let params = {
          dbCode: formObj.dbCode,
          tableNames: val.name,
        };
        let chlidKey: any = ref();
        if (val.type === 'chlid') {
          getOutKeyList(params).then((res: Recordable) => {
            if (res[0]) {
              res[0].db_codecolumnsList.forEach((item) => {
                if (item.isPrimaryKey == 1) {
                  chlidKey.value = item.dbColumnName;
                }
              });
            }
          });
        }
        formObj.formInfo.schemas.forEach((item) => {
          if (
            item.componentProps.dataTable == val.name &&
            formObj.primaryKey == item.componentProps.fieldName
          ) {
            arr.push({
              type: val.type,
              field: item.field,
            });
          }
          if (
            val.type == 'chlid' &&
            val.name == item.componentProps.dataTable &&
            chlidKey.value == item.componentProps.fieldName
          ) {
            arr.push({
              type: val.type,
              field: item.field,
            });
          }
        });
      });
      let newArr: any = [...new Set(arr)];
      addQuery.value = [];
      if (newArr && !unref(isUpdate)) {
        newArr.forEach((item) => {
          addQuery.value.push({
            type: item.type,
            field: item.field,
            value: generateUniqueDigits(20).join(''),
          });
        });
      }

      if (formObj.primaryKey) {
        getFormDetail(formObj.primaryKey);
      }
    });
  }
  function getFormDetail(key: '') {
    if (!paramsKeyValue) {
      return;
    }
    let params = {
      id: schemeId.value,
      key: key,
      keyValue: paramsKeyValue,
    };
    getFormsDataDetail(params).then((res: Recordable) => {
      if (res) {
        let obj: any = {};
        res.forEach((item) => {
          obj[item.columnName] = item.value;
        });
        setFieldsValue(obj);
      }
    });
  }
  onMounted(() => {
    getPublicForm();
  });
  const prefixCls = 'form-box';
</script>
<style lang="less" scoped>
  .form-box {
    width: 100%;
    height: 100%;
    background: #eceff9;

    &-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80px;
      background: #fff;
      font-size: 16px;
    }

    &-content {
      height: calc(100% - 220px);
      padding: 20px;
      overflow: auto;
    }

    &-footer {
      position: fixed;
      bottom: 30px;
      width: 100%;

      &-cancle {
        width: 94%;
        height: 50px;
        margin-top: 10px;
        margin-left: 3%;
        border-radius: 4px;
        background: #fff;
        color: #a7afd0;
        font-size: 18px;
        line-height: 50px;
        text-align: center;
      }

      &-confirm {
        width: 94%;
        height: 50px;
        margin-left: 3%;
        border-radius: 4px;
        background: #1e5eff;
        color: #fff;
        font-size: 18px;
        line-height: 50px;
        text-align: center;
      }
    }
  }
</style>
