<template>
  <div class="show-form-modal" style="width: 100%">
    <div class="title">
      <div class="close-button"><ArrowLeftOutlined @click="closeModal" /></div>
      <div>{{ getTitle }}</div>
    </div>
    <div class="form-content">
      <BasicForm ref="myDataBaseFormRef" @register="registerForm" v-if="formModalVisible" />
      <a-table
        class="sub-table"
        :columns="subTableColumns"
        :data-source="subTableList"
        :pagination="false"
        :customRow="customRow"
        v-if="subTableId"
        :scroll="scrollValue"
      >
        <template #headerCell="{ column, record }">
          <template v-if="column.key === 'setting'">
            <PlusOutlined class="icon-button" @click="insertListItem()" />
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'setting'">
            <DeleteOutlined class="icon-button" @click="delListItem(column, record)" />
          </template>
          <template v-else>
            <FormItem :data="column" :record="record" />
          </template>
        </template>
      </a-table>
    </div>
    <div class="footer-button" v-if="!isDetail">
      <a-button style="margin-right: 20px" @click="closeModal">取消</a-button>
      <a-button type="primary" @click="ModalSureClick">确认</a-button>
    </div>
  </div>
</template>

<script setup lang="tsx">
  import { defineEmits, defineProps, ref, onMounted, unref, reactive, toRaw, h } from 'vue';
  import { ArrowLeftOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { FormSchema } from '@/components/Table';
  import { create, saveDraft } from '@/api/sys/WFProcess';
  import { saveFormsData } from '@/api/formrender/index';
  import { addGeom } from '@/api/sys/layerManagement';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import FormItem from './FormItem/index.vue';
  import { v4 as uuidv4 } from 'uuid';
  const { createMessage } = useMessage();
  const myDataBaseFormRef = ref();
  const props = defineProps([
    'open',
    'showFormModalData',
    'mapgemoList',
    'formData',
    "geometryForm",
    'MapboxComponent',
    'mapSetData',
    'haveMap',
  ]);
  const emits = defineEmits(['closeShowFormModal', 'setSelectedSubTableDataId']);
  const subTableList = ref();
  const subTableId = ref(null);
  const isUpdate = ref(false);
  const isDetail = ref(false);
  const flowCode = ref('');
  const getTitle = ref('');
  const formColumns: FormSchema[] = [];
  const addQuery: any = ref([]);
  const formModalVisible = ref(false);
  const primaryQuery = ref();
  const userStore = useUserStore();
  const userInfo: any = userStore.getUserInfo;
  const formData = reactive({
    userId: userInfo.id,
    title: '',
  });
  const scrollValue = ref();
  const subTableColumns = ref([
    {
      dataIndex: 'setting',
      key: 'setting',
      fixed: 'left',
      width: 60,
    },
  ]);
  const subTableData = ref([]);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formColumns,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });
  const customRow = (record) => {
    return {
      onClick: (event) => {
        if (!props.haveMap) return;
        let mapDataList = [
          {
            columnName: 'mapgeom',
            value: record.MapGeom || null,
          },
        ];
        if (unref(isDetail)) {
          props.MapboxComponent.handlerDraw(mapDataList, false);
          return;
        }
        emits('setSelectedSubTableDataId', record.key);
        if (record.isInsert) {
          props.mapSetData.isAllowAddPolygon &&
            props.MapboxComponent.handlerDraw(mapDataList, true);
        } else {
          props.MapboxComponent.handlerDraw(mapDataList, props.mapSetData.isAllowEditPolygon);
        }
        if (record.MapGeom.length > 0 && props.mapSetData.isEnablePostionJump) {
          let jumpDataString = record.MapGeom;
          let jumpDataList = jumpDataString.replace(/[A-Z|(|)]/g, '').split(' ');

          if (jumpDataString.slice(0, 5) === 'POINT') {
            let jumpData =
              jumpDataList[0].length > 0
                ? [jumpDataList[0], jumpDataList[1]]
                : [jumpDataList[1], jumpDataList[2]];
            props.MapboxComponent.handlerLocation(jumpData);
          } else {
            let jumpData =
              jumpDataList[0].length > 0
                ? [jumpDataList[0], jumpDataList[1].split(',')[0]]
                : [jumpDataList[1], jumpDataList[2].split(',')[0]];
            props.MapboxComponent.handlerLocation(jumpData);
          }
        }
      },
    };
  };
  const closeModal = () => {
    emits('closeShowFormModal', 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);
  }

  onMounted(() => {
    const data = props.showFormModalData;
    console.log("showFormModalData",props.showFormModalData)
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.isDetail;
    data.tab.forEach((item) => {
      if (item.rules !== undefined) {
        let myString = item.rules[0].pattern;
        const lastCharacter = myString.charAt(myString.length - 1);
        if (lastCharacter === 'i' || lastCharacter === 's') {
          item.rules[0].pattern = new RegExp(item.rules[0].pattern.slice(1, -2), lastCharacter);
        } else {
          item.rules[0].pattern = new RegExp(item.rules[0].pattern.slice(1, -1));
        }
      }
      formColumns.push(item);
      if (item.type === 'subTable') {
        subTableId.value = item.field;
        let tableData = [];
        item.columns.forEach((itemColumn) => {
          itemColumn.children.forEach((itemColumnChild) => {
            tableData.push(itemColumnChild);
            subTableColumns.value.push({
              key: itemColumnChild.field,
              title: itemColumnChild.label,
              dataIndex: itemColumnChild.field,
              width: 120,
              ...itemColumnChild,
            });
          });
        });
        scrollValue.value = { x: (subTableColumns.value.length - 1) * 140, y: 300 };
        subTableData.value = tableData;
      }
    });

    if (!unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '新增';
      data.btnList.forEach((element) => {
        if (element.prop === 'Add' && element.isWFlow) {
          flowCode.value = element.wFlowCode;
        }
      });
      subTableList.value = toRaw(props.formData);
    }
    if (unref(isUpdate) && !unref(isDetail)) {
      getTitle.value = '编辑';
      data.btnList.forEach((element) => {
        if (element.prop === 'Edit' && element.isWFlow) {
          flowCode.value = element.wFlowCode;
        }
      });
      subTableList.value = toRaw(props.formData);
    }
    if (!unref(isUpdate) && unref(isDetail)) {
      getTitle.value = '详情';
      subTableList.value = toRaw(props.formData);
    }
    formModalVisible.value = true;
    primaryQuery.value = data.query;
    if (data.record) {
      setTimeout(() => {
        setFieldsValue({
          ...data.record,
        });
      }, 100);
    } else {
      myDataBaseFormRef.value && resetFields();
    }
    addQuery.value = [];
    if (data.addParams) {
      data.addParams.forEach((item) => {
        addQuery.value.push({
          type: item.type,
          field: item.field,
          value: generateUniqueDigits(20).join(''),
        });
      });
    }
  });

  


  //表单填写数据
  async function ModalSureClick() {

    // 如果有地图，先调用保存地图函数保存完线索数据后获取线索数据再将线索id保存到主表
    // addGeom(props.geometryForm).then(res=>{
    //   console.log("addGeom",res)
    // })

    try {
      const values = await validate();
      let query = values;
      let mapGeomList = toRaw(props.mapgemoList).map((item) => {
        return item.value;
      });
      let saveSubTableList = [];
      subTableList.value.forEach((item) => {
        let emptyObj = {};
        for (const key in item) {
          if (key.indexOf('guid') !== -1 && item[key] == '') {
            let guid = generateUniqueDigits(20).join('');
            item[key] = guid;
            emptyObj[key] = guid;
          }
          if (key === 'key') continue;
          if (key === 'isInsert') continue;
          emptyObj[key] = item[key];
        }
        saveSubTableList.push(emptyObj);
      });
      query[subTableId.value] = JSON.stringify(saveSubTableList);
      query.MapGeom = mapGeomList.join(';');
      let params: any = {
        schemeId: primaryQuery.value.id,
        isUpdate: isUpdate.value,
        pkey: primaryQuery.value.key,
      };
      if (unref(isUpdate)) {
        params.pkeyValue = primaryQuery.value.keyValue;
      } 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) {
        emits('success');
        if (flowCode.value == '') {
          closeModal();
        } else {
          handleCreateFlow(params.pkeyValue);
        }
        return createMessage.success('操作成功');
      } else {
        return createMessage.error('操作失败');
      }
    } catch (error) {
      console.log(error);
    }
  }
  async function handleCreateFlow(processId) {
    var querys = {
      schemeCode: flowCode.value,
      userId: formData.userId,
      title: formData.title,
      processId: processId,
    };
    const draft = await saveDraft(querys);
    if (draft) {
      querys.schemeCode = '';
      const data = await create(querys);
      if (data) {
        closeModal();
        return createMessage.success('发起流程成功');
      } else {
        return createMessage.error('发起流程失败');
      }
    } else {
      return createMessage.error('保存草稿失败');
    }
  }
  const insertListItem = () => {
    let keyList = subTableData.value.map((item) => {
      return item.field;
    });
    let emptyItem = { key: uuidv4(), isInsert: true };
    keyList.forEach((item) => {
      emptyItem[item] = '';
    });
    subTableList.value.push(emptyItem);
  };
  const delListItem = (column, record) => {
    subTableList.value = subTableList.value.filter((item) => item.key != record.key);
  };

  // 保存geom数据，拼接生成的主键并返回
  const handlerSaveGeom = (geomForm) => {
    try{
      addGeom(geomForm).then(res=>{
        console.log("geom-res",res);
      })
    }catch{

    }
    
  }
</script>

<style lang="scss" scoped>
  .icon-button {
    cursor: pointer;
  }
  .show-form-modal {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    background-color: #fff;
    z-index: 4;
    padding: 30px;
    .title {
      font-size: 16px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ccc;
      height: 50px;
      align-items: center;
      .close-button {
        opacity: 0.7;
      }
      .close-button:hover {
        opacity: 1;
      }
    }
    .form-content {
      padding: 25px 25px 0px 25px;
      height: calc(100% - 97px);
      display: flex;
      flex-direction: column;
      // justify-content: space-between;
      overflow: auto;
      margin-bottom: 15px;
    }
    .footer-button {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
<style lang="scss">
  .show-form-modal {
    .form-content {
      .sub-table {
        .ant-table-tbody {
          .ant-table-cell {
            .anticon-delete {
              opacity: 0;
            }
          }
          .ant-table-cell-row-hover {
            .anticon-delete {
              opacity: 1;
              color: red;
            }
          }
        }
      }
    }
  }
</style>
