<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    width="600px"
    :minHeight="100"
    :cancelText="t('common.cancelText', '取消')"
    :okText="t('common.okText', '确定')"
    @ok="handleSubmit"
    :closeFunc="onClose">
    <template #title>
      <a-space :size="10">
        <div class="text-16px font-medium">{{ title }}</div>
      </a-space>
    </template>
    <a-row class="dynamic-form">
      <a-form
        :colon="false"
        size="middle"
        layout="horizontal"
        labelAlign="right"
        :labelCol="{ style: { width: '100px' } }"
        :model="dataForm"
        :rules="dataRule"
        ref="formRef">
        <a-row :gutter="15">
          <!-- 具体表单 -->
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="project_code">
              <template #label>项目编码 </template>
              <YunzhupaasInput
                v-model:value="dataForm.project_code"
                @change="changeData('project_code', -1)"
                placeholder="请输入"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.project_code"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="project_name">
              <template #label>项目名称 </template>
              <YunzhupaasInput
                v-model:value="dataForm.project_name"
                @change="changeData('project_name', -1)"
                placeholder="请输入"
                :allowClear="true"
                :style="{ width: '100%' }"
                :maskConfig="maskConfig.project_name"
                :showCount="false">
              </YunzhupaasInput>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="project_type_id">
              <template #label>项目类型 </template>
              <YunzhupaasTreeSelect
                v-model:value="dataForm.project_type_id"
                @change="changeData('project_type_id', -1)"
                placeholder="请选择"
                :templateJson="state.interfaceRes.project_type_id"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.project_type_idOptions"
                :fieldNames="optionsObj.project_type_idProps">
              </YunzhupaasTreeSelect>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="org_id">
              <template #label>归属组织 </template>
              <YunzhupaasOrganizeSelect
                v-model:value="dataForm.org_id"
                @change="changeData('org_id', -1)"
                placeholder="请选择"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                selectType="all">
              </YunzhupaasOrganizeSelect>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="pid">
              <template #label>上级项目 </template>
              <YunzhupaasTreeSelect
                v-model:value="dataForm.pid"
                @change="changeData('pid', -1)"
                placeholder="请选择"
                :templateJson="state.interfaceRes.pid"
                :allowClear="true"
                :style="{ width: '100%' }"
                :showSearch="false"
                :options="optionsObj.pidOptions"
                :fieldNames="optionsObj.pidProps">
              </YunzhupaasTreeSelect>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="seq_num">
              <template #label>顺序号 </template>
              <YunzhupaasInputNumber
                v-model:value="dataForm.seq_num"
                @change="changeData('seq_num', -1)"
                placeholder="请输入"
                :style="{ width: '100%' }"
                :step="1"
                :controls="false">
              </YunzhupaasInputNumber>
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item">
            <a-form-item name="remark">
              <template #label>备注 </template>
              <YunzhupaasTextarea
                v-model:value="dataForm.remark"
                @change="changeData('remark', -1)"
                placeholder="请输入"
                :allowClear="true"
                :style="{ width: '100%' }"
                :autoSize="{ minRows: 4, maxRows: 4 }"
                :showCount="false">
              </YunzhupaasTextarea>
            </a-form-item>
          </a-col>
          <!-- 表单结束 -->
        </a-row>
      </a-form>
    </a-row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { create, update, getInfo ,getProjectTreeList} from './helper/api';
    import { getTreeList} from '@/views/bsc/projecttype/helper/api';
  import { reactive, toRefs, nextTick, ref, unref, computed, toRaw, inject } from 'vue';
  import { BasicModal, useModal } from '@/components/Modal';
  import { yunzhupaasRelationForm } from '@/components/yunzhupaas';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useUserStore } from '@/store/modules/user';
  import type { FormInstance } from 'ant-design-vue';
  import { thousandsFormat, getDateTimeUnit, getTimeUnit } from '@/utils/yunzhupaas';
  import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
  import { getDataInterfaceRes } from '@/api/systemData/dataInterface';
  import dayjs from 'dayjs';
  // 表单权限
  import { usePermission } from '@/hooks/web/usePermission';
  import { cloneDeep } from 'lodash-es';
  import { buildUUID } from '@/utils/uuid';
  import { CaretRightOutlined } from '@ant-design/icons-vue';

  interface State {
    dataForm: any;
    tableRows: any;
    dataRule: any;
    optionsObj: any;
    childIndex: any;
    isEdit: any;
    interfaceRes: any;
    //可选范围默认值
    ableAll: any;
    //掩码配置
    maskConfig: any;
    //定位属性
    locationScope: any;
    extraOptions: any;
    title: string;
    continueText: string;
    allList: any[];
    currIndex: number;
    isContinue: boolean;
    submitType: number;
    showContinueBtn: boolean;
  }

  const emit = defineEmits(['reload']);
  const getLeftTreeActiveInfo: (() => any) | null = inject('getLeftTreeActiveInfo', null);
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const { createMessage, createConfirm } = useMessage();
  const { t } = useI18n();
  const [registerModal, { openModal, setModalProps }] = useModal();
  const formRef = ref<FormInstance>();
  const state = reactive<State>({
    dataForm: {
      project_code: undefined,
      project_name: undefined,
      project_type_id: '',
      org_id: userInfo.organizeIdList ? userInfo.organizeIdList : '',
      pid: '',
      seq_num: undefined,
      remark: undefined,
    },

    tableRows: {},

    dataRule: {
            project_code: [
                {
                required: true,
                message: t('sys.validate.textRequiredSuffix','不能为空'),
                trigger: 'blur'
                },
            ],
                project_name: [
                {
                required: true,
                message: t('sys.validate.textRequiredSuffix','不能为空'),
                trigger: 'blur'
                },
            ],
                org_id: [
                {
                required: true,
                message: t('sys.validate.arrayRequiredPrefix	','请至少选择一个'),
                trigger: 'change'
                },
            ],
    },

    optionsObj: {
      project_type_idOptions: [],
      project_type_idProps: { label: 'projectTypeName', value: 'projectTypeId', children: 'children' },
      pidOptions: [],
      pidProps: { label: 'projectName', value: 'projectId', children: 'children' },
    },

    childIndex: -1,
    isEdit: false,
    interfaceRes: { project_type_id: [], org_id: [], project_code: [], pid: [], remark: [], project_name: [], seq_num: [] },
    //可选范围默认值
    ableAll: {},

    //掩码配置
    maskConfig: {
      project_code: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
      project_name: {
        prefixType: 1,
        useUnrealMask: false,
        maskType: 1,
        unrealMaskLength: 1,
        prefixLimit: 0,
        suffixLimit: 0,
        filler: '*',
        prefixSpecifyChar: '',
        suffixType: 1,
        ignoreChar: '',
        suffixSpecifyChar: '',
      },
    },

    //定位属性
    locationScope: {},

    extraOptions: {},

    title: '',
    continueText: '',
    allList: [],
    currIndex: 0,
    isContinue: false,
    submitType: 0,
    showContinueBtn: true,
  });
  const { title, continueText, showContinueBtn, dataRule, dataForm, optionsObj, ableAll, maskConfig, submitType } = toRefs(state);

  const getPrevDisabled = computed(() => state.currIndex === 0);
  const getNextDisabled = computed(() => state.currIndex === state.allList.length - 1);
  // 表单权限
  const { hasFormP } = usePermission();

  defineExpose({ init });

  function init(data) {
    state.submitType = 0;
    state.isContinue = false;
    state.title = !data.id ? t('common.add2Text', '新增') : t('common.editText', '编辑');
    state.continueText = !data.id ? t('common.continueAndAddText', '确定并新增') : t('common.continueText', '确定并继续');
    setFormProps({ continueLoading: false });
    state.dataForm.id = data.id;
    openModal();
    state.allList = data.allList;
    state.currIndex = state.allList.length && data.id ? state.allList.findIndex(item => item.id === data.id) : 0;
    nextTick(() => {
      getForm().resetFields();
      setTimeout(initData, 0);
    });
  }
  function initData() {
    changeLoading(true);
    if (state.dataForm.id) {
      getData(state.dataForm.id);
    } else {
      //初始化options
      getproject_type_idOptions();
      getpidOptions();

      // 设置默认值
      state.dataForm = {
        project_code: undefined,
        project_name: undefined,
        project_type_id: '',
        org_id: userInfo.organizeIdList ? userInfo.organizeIdList : '',
        pid: '',
        seq_num: undefined,
        remark: undefined,
      };
      if (getLeftTreeActiveInfo) state.dataForm = { ...state.dataForm, ...(getLeftTreeActiveInfo() || {}) };
      state.childIndex = -1;
      changeLoading(false);
    }
  }
  function getForm() {
    const form = unref(formRef);
    if (!form) {
      throw new Error('form is null!');
    }
    return form;
  }
  function getData(id) {
    getInfo(id).then(res => {
      state.dataForm = res.data || {};
      getproject_type_idOptions();
      getpidOptions();

      state.childIndex = -1;
      changeLoading(false);
    });
  }
  async function handleSubmit(type) {
    try {
      const values = await getForm()?.validate();
      if (!values) return;

      setFormProps({ confirmLoading: true });
      const formMethod = state.dataForm.id ? update : create;
      console.log(state.dataForm);
      
      formMethod(state.dataForm)
        .then(res => {
          createMessage.success(res.msg);
          setFormProps({ confirmLoading: false });
          if (state.submitType == 1) {
            initData();
            state.isContinue = true;
          } else {
            setFormProps({ open: false });
            emit('reload');
          }
        })
        .catch(() => {
          setFormProps({ confirmLoading: false });
        });
    } catch (_) {}
  }
  function handlePrev() {
    state.currIndex--;
    handleGetNewInfo();
  }
  function handleNext() {
    state.currIndex++;
    handleGetNewInfo();
  }
  function handleGetNewInfo() {
    changeLoading(true);
    getForm().resetFields();
    const id = state.allList[state.currIndex].id;
    getData(id);
  }
  function setFormProps(data) {
    setModalProps(data);
  }
  function changeLoading(loading) {
    setModalProps({ loading });
  }
  async function onClose() {
    if (state.isContinue) emit('reload');
    return true;
  }

  function changeData(model, index) {
    state.isEdit = false;
    state.childIndex = index;
    for (let key in state.interfaceRes) {
      if (key != model) {
        let faceReList = state.interfaceRes[key];
        for (let i = 0; i < faceReList.length; i++) {
          let relationField = faceReList[i].relationField;
          if (relationField) {
            let modelAll = relationField.split('-');
            let faceMode = '';
            let faceMode2 = modelAll.length == 2 ? modelAll[0].substring(0, modelAll[0].length - 4) + modelAll[1] : '';
            for (let i = 0; i < modelAll.length; i++) {
              faceMode += modelAll[i];
            }
            if (faceMode == model || faceMode2 == model) {
              let options = 'get' + key + 'Options';
              eval(options)(true);
              changeData(key, index);
            }
          }
        }
      }
    }
  }
  function changeDataFormData(type, data, model, index, defaultValue) {
    if (!state.isEdit) {
      if (type == 2) {
        for (let i = 0; i < state.dataForm[data].length; i++) {
          if (index == -1) {
            state.dataForm[data][i][model] = defaultValue;
          } else if (index == i) {
            state.dataForm[data][i][model] = defaultValue;
          }
        }
      } else {
        state.dataForm[data] = defaultValue;
      }
    }
  }
  //数据选项--远端数据初始化方法
  function getproject_type_idOptions(isClear = false) {
    

    const index = state.childIndex;
    let templateJsonList = JSON.parse(JSON.stringify(state.interfaceRes.project_type_id));
    for (let i = 0; i < templateJsonList.length; i++) {
      let json = templateJsonList[i];
      if (json.relationField && json.sourceType == 1) {
        let relationFieldAll = json.relationField.split('-');
        let val = json.defaultValue;
        if (relationFieldAll.length > 1 && index > -1) {
          if (relationFieldAll[0].endsWith('List')) {
            val =
              state.dataForm[relationFieldAll[0]] && state.dataForm[relationFieldAll[0]].length
                ? state.dataForm[relationFieldAll[0]][index][relationFieldAll[1]]
                : '';
          } else {
            val =
              state.dataForm[relationFieldAll[0] + 'List'] && state.dataForm[relationFieldAll[0] + 'List'].length
                ? state.dataForm[relationFieldAll[0] + 'List'][index][relationFieldAll[1]]
                : '';
          }
        } else {
          val = state.dataForm[relationFieldAll];
        }
        json.defaultValue = val ? val : '';
      }
    }
    // let template = {
    //   paramList: templateJsonList,
    // };
     getTreeList().then(res => {
      state.optionsObj.project_type_idOptions = res.data || [];
          if (index == -1) return;
      if (isClear) {
        changeDataFormData(1, 'List', 'project_type_id', index, '');
      }
    });
    // getDataInterfaceRes('824687938385216645', template).then(res => {
    //   let data = res.data;
    //   state.optionsObj.project_type_idOptions = data;
    //   if (index == -1) return;
    //   if (isClear) {
    //     changeDataFormData(1, 'List', 'project_type_id', index, '');
    //   }
    // });
  }
  //数据选项--远端数据初始化方法
  function getpidOptions(isClear = false) {
   
    const index = state.childIndex;
    let templateJsonList = JSON.parse(JSON.stringify(state.interfaceRes.pid));
    for (let i = 0; i < templateJsonList.length; i++) {
      let json = templateJsonList[i];
      if (json.relationField && json.sourceType == 1) {
        let relationFieldAll = json.relationField.split('-');
        let val = json.defaultValue;
        if (relationFieldAll.length > 1 && index > -1) {
          if (relationFieldAll[0].endsWith('List')) {
            val =
              state.dataForm[relationFieldAll[0]] && state.dataForm[relationFieldAll[0]].length
                ? state.dataForm[relationFieldAll[0]][index][relationFieldAll[1]]
                : '';
          } else {
            val =
              state.dataForm[relationFieldAll[0] + 'List'] && state.dataForm[relationFieldAll[0] + 'List'].length
                ? state.dataForm[relationFieldAll[0] + 'List'][index][relationFieldAll[1]]
                : '';
          }
        } else {
          val = state.dataForm[relationFieldAll];
        }
        json.defaultValue = val ? val : '';
      }
    }
    // let template = {
    //   paramList: templateJsonList,
    // };
        getProjectTreeList().then(res => {
      state.optionsObj.pidOptions = res.data || [];
         if (index == -1) return;
      if (isClear) {
        changeDataFormData(1, 'List', 'pid', index, '');
      }
    });
    // getDataInterfaceRes('826399583931205381', template).then(res => {
    //   let data = res.data;
    //   state.optionsObj.pidOptions = data;
    //   if (index == -1) return;
    //   if (isClear) {
    //     changeDataFormData(1, 'List', 'pid', index, '');
    //   }
    // });
  }
  function getRelationDate(timeRule, timeType, timeTarget, timeValueData, dataValue) {
    let timeDataValue: any = null;
    let timeValue = Number(timeValueData);
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue;
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = new Date().getTime();
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).valueOf();
      }
    }
    return timeDataValue;
  }
  function getRelationTime(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
    let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType;
    let timeDataValue: any = null;
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue || '00:00:00';
        if (timeDataValue.split(':').length == 3) {
          timeDataValue = timeDataValue;
        } else {
          timeDataValue = timeDataValue + ':00';
        }
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = dayjs().format(format);
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget + 3);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).format(format);
      }
    }
    return timeDataValue;
  }
</script>
