<template>
  <h-b-form ref="formRef" name="use" v-bind="formProps" :model="model"></h-b-form>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, onMounted, reactive } from 'vue';
import { useForm } from '@crami/bui-platform';
import { HModal, message } from '@crami/ui';
import { BForm as HBForm } from '@crami/bui';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const props = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'EditCodeSegment',
  props: props,
  components: {
    HBForm,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const isEdit = props.componentProps?.params?.isEdit || false;
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    let baseHidden = true;
    let isDay = false;
    const editCode = {
      pid: null,
      pname: null,
      level: '',
    };
    const thinDatas = reactive([]);
    const lengthDatas = reactive([]);
    const parentDatas = reactive([]);

    // 第二种方法，useForm调用查询方法
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        immediate: true,
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form',
            productLine:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.project
                : '',
            mode: 'edit',
            name:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.modelName
                : '',
          },
          method: 'post',
        },
        saveApi:
          props.componentProps?.params?.saveDataParams?.saveUrl?.length > 0
            ? {
                url: props.componentProps?.params?.saveDataParams?.saveUrl,
                method: 'post',
                type: 'json',
              }
            : {},
        dataSourceApi: {
          url: '/api/system/model/GetObjectDataTestList',
          method: 'post',
          params: {
            objectID: props.componentProps?.params?.objectID?.EID || {},
            companyId: commonParams.value?.companyId,
            connect: commonParams.value?.connect,
            userId: commonParams.value.user_id,
            lang: commonParams.value?.lang,
            timeZone: commonParams.value?.TIME_ZONE,
          },
        },
        // 设置form的各种配置信息
        beforeSetData: (type, prop) => {
          if (type === 'data') {
            Object.assign(model, prop);
            if (prop.ROUGH_RULES) {
              // getCodeRulesData(prop.ROUGH_RULES);
              selectUseClick(prop.ROUGH_RULES, false);
              if (prop.ROUGH_RULES === 'DATE') {
                getCodeDayData(prop.FINE_RULES, false);
              }
            }
            if (prop.PID) {
              editCode.pid = prop.PID;
              // model['PNAME'] = prop.PID;
            }
            if (prop.PNAME) {
              editCode.pname = prop.PNAME;
            }
            if (prop.LEVEL) {
              editCode.level = prop.LEVEL + '';
            }
          }

          if (type === 'config') {
            const _props: any = {
              isQuery: false,
              uniqueParams: uniqueParams(),
              submitter: {
                showActionButtonGroup: false,
                isQuery: false,
              },
            };
            formMethods.setProps(_props, prop);
            isDay = false;

            if (model['ROUGH_RULES'] === 'PIPELINE_CODE') {
              baseHidden = false;
            } else if (model['ROUGH_RULES'] === 'DATE') {
              isDay = true;
              baseHidden = true;
            } else {
              baseHidden = true;
            }
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'LENGTH',
                  valueType: isDay ? 'Select' : 'Input',
                  disabled: isEdit,
                  fieldProps: {
                    options: lengthDatas,
                    onChange: changeLENGTH,
                  },
                  formItemProps: {},
                },
                {
                  dataIndex: 'ROUGH_RULES',
                  valueType: 'Select',
                  disabled: isEdit,
                  fieldProps: {
                    onSelect: selectUseClick,
                  },
                  width: baseHidden ? '50%' : '33%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'FINE_RULES',
                  valueType: 'Select',
                  disabled: isEdit,
                  fieldProps: {
                    options: thinDatas,
                    onSelect: selectFineClick,
                  },
                  width: baseHidden ? '50%' : '33%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'INIT_CODE',
                  valueType: 'Input',
                  renderFormItem: !baseHidden,
                  width: '50%',
                  formItemProps: {},
                  dynamicRules: () => {
                    //监听正则变化
                    let pattern = '';
                    if (model['LENGTH'] == 0) {
                      pattern = '^' + model['FINE_RULES'] + '{0,20}$';
                    } else if (model['LENGTH']) {
                      pattern = '^' + model['FINE_RULES'] + '{0,' + model['LENGTH'] + '}$';
                    } else {
                      pattern =
                        '^' +
                        model['FINE_RULES'] +
                        '{0,' +
                        (model['LENGTH'] == 0 ? 20 : model['LENGTH']) +
                        '}$';
                    }

                    return [
                      {
                        message: t('code.codeSegment.createOrEditCodeSegment.initCode'),
                        pattern: pattern,
                        trigger: 'change',
                        required: false,
                      },
                    ];
                  },
                },
                {
                  dataIndex: 'RESTART',
                  renderFormItem: !baseHidden,
                  fieldProps: {},
                  disabled: isEdit,
                  width: '33%',
                  formItemProps: {
                    rules: [
                      {
                        message: t('code.codeSegment.createOrEditCodeSegment.restartMsg'),
                        pattern: '^\\s*(\\S+\\s*)+$',
                        trigger: 'change',
                        required: true,
                      },
                    ],
                  },
                },
                {
                  dataIndex: 'PNAME',
                  valueType: 'Select',
                  disabled: isEdit,
                  fieldProps: {
                    placeholder: isEdit ? '' : '请选择',
                    options: parentDatas,
                    onChange: changePidClick,
                  },
                  formItemProps: {},
                },
              ],
              prop,
            );
          }

          return prop;
        },
      },
      undefined,
      emit,
      {
        isAdd: false,
        ...(props.componentProps?.params || {}),
      },
    );
    //长度改变进行验证
    const changeLENGTH = () => {
      formMethods.updateSchema([
        {
          dataIndex: 'INIT_CODE',
          valueType: 'Input',
          renderFormItem: !baseHidden,
          dynamicRules: () => {
            //监听正则变化
            let pattern = '';
            if (model['LENGTH'] == 0) {
              pattern = '^' + model['FINE_RULES'] + '{0,20}$';
            } else if (model['LENGTH']) {
              pattern = '^' + model['FINE_RULES'] + '{0,' + model['LENGTH'] + '}$';
            } else {
              pattern =
                '^' +
                model['FINE_RULES'] +
                '{0,' +
                (model['LENGTH'] == 0 ? 20 : model['LENGTH']) +
                '}$';
            }

            return [
              {
                message: t('code.codeSegment.createOrEditCodeSegment.initCode'),
                pattern: pattern,
                trigger: 'change',
                required: false,
              },
            ];
          },
          formItemProps: {},
        },
      ]);
      if (model['INIT_CODE']) {
        nextTick(() => {
          formRef.value?.validateFields('INIT_CODE');
        });
      }
    };
    const submitter = reactive({
      isQuery: false, // 是否为查询表单
      submitOnReset: false,
      searchConfig: { resetText: t('code.common.cancel') },
      onReset: () => {
        formMethods.clearValidate();
        // emit('end');
        HModal.destroyAll();
      },
    });
    formProps.submitter = submitter;

    const model = reactive({});

    const uniqueParams = () => {
      return {
        objectType:
          props.componentProps.params != undefined ? props.componentProps.params.modelName : '', //唯一性校验
        NewObject: true, //唯一性校验
        connect: commonParams.value?.connect,
        // type: 'model',
        lang: commonParams.value?.lang,
      };
    };

    const changePidClick = (event: any) => {
      if (event === undefined) {
        editCode.pid = null;
        editCode.pname = null;
        editCode.level = null;
        return;
      }
      editCode.pid = event;
      for (let i = 0; i < parentDatas.length; i++) {
        const item = parentDatas[i];
        if (item.value === event) {
          editCode.pname = item.label;
          editCode.level = item.level;
          break;
        }
      }
    };

    const selectUseClick = (event: any, isChange = true) => {
      isDay = false;
      if (event === 'PIPELINE_CODE') {
        baseHidden = false;
      } else if (event === 'DATE') {
        isDay = true;
        baseHidden = true;
        if (isChange) {
          model['RESTART'] = '';
          model['INIT_CODE'] = '';
          model['LENGTH'] = undefined;
        }
      } else {
        baseHidden = true;
        if (isChange) {
          model['INIT_CODE'] = '';
          model['RESTART'] = '';
        }
      }
      getCodeRulesData(event, isChange);
      formMethods.updateSchema(
        [
          {
            dataIndex: 'LENGTH',
            valueType: isDay ? 'Select' : 'Input',
            disabled: isEdit,
            fieldProps: {
              options: lengthDatas,
            },
            formItemProps: {},
          },
          {
            dataIndex: 'ROUGH_RULES',
            valueType: 'Select',
            disabled: isEdit,
            fieldProps: {
              onSelect: selectUseClick,
            },
            width: baseHidden ? '50%' : '33%',
            formItemProps: {},
          },
          {
            dataIndex: 'FINE_RULES',
            valueType: 'Select',
            disabled: isEdit,
            fieldProps: {
              options: thinDatas,
              onSelect: selectFineClick,
            },
            width: baseHidden ? '50%' : '33%',
            formItemProps: {},
          },
          {
            dataIndex: 'RESTART',
            renderFormItem: !baseHidden,
            fieldProps: {},
            disabled: isEdit,
            width: '33%',
            formItemProps: {
              rules: [
                {
                  message: t('code.codeSegment.createOrEditCodeSegment.restartMsg'),
                  pattern: '^\\s*(\\S+\\s*)+$',
                  trigger: 'change',
                  required: true,
                },
              ],
            },
          },
          {
            dataIndex: 'INIT_CODE',
            valueType: 'Input',
            renderFormItem: !baseHidden,
            width: '50%',
            formItemProps: {},
            dynamicRules: () => {
              //监听正则变化
              let pattern = '';
              if (model['LENGTH'] == 0) {
                pattern = '^' + model['FINE_RULES'] + '{0,20}$';
              } else if (model['LENGTH']) {
                pattern = '^' + model['FINE_RULES'] + '{0,' + model['LENGTH'] + '}$';
              } else {
                pattern =
                  '^' +
                  model['FINE_RULES'] +
                  '{0,' +
                  (model['LENGTH'] == 0 ? 20 : model['LENGTH']) +
                  '}$';
              }

              return [
                {
                  message: t('code.codeSegment.createOrEditCodeSegment.initCode'),
                  pattern: pattern,
                  trigger: 'change',
                  required: false,
                },
              ];
            },
          },
          {
            dataIndex: 'PNAME',
            valueType: 'Select',
            disabled: isEdit,
            fieldProps: {
              placeholder: isEdit ? '' : '请选择',
              options: parentDatas,
              onChange: changePidClick,
            },
            formItemProps: {},
          },
        ],
        props,
      );
    };

    const selectFineClick = (event: any) => {
      getCodeDayData(event);
    };

    const onFinish = () => {
      formMethods
        .validate()
        .then(res => {
          //   emit('end', { success: true, code: 200, msg: 'ddd' });
          //   provide('proCreateCode', { success: true, code: 200, msg: '' });
          submitApi(res);
        })
        .catch(err => {
          console.info('---validate', err);
        });
    };

    onMounted(() => {
      getParentData();
    });

    const submitApi = async (res: any) => {
      const params = {
        schemeId: props.componentProps?.params.codeSchemeId,
        segmentName: res.ENAME,
        length: res.LENGTH,
        roughRules: res.ROUGH_RULES,
        fineRules: res.FINE_RULES,
        codeSeparator: res.CODE_SEPARATOR,
        parentName: editCode.pname,
        parentId: editCode.pid,
        level: editCode.level,
        restart: res.RESTART,
        describes: res.DESCRIBES,
        connect: commonParams.value?.connect,
        lang: commonParams.value?.lang,
        companyId: commonParams.value?.companyId,
        userId: commonParams.value?.user_id,
        segmentId: props.componentProps?.params.objectID.EID,
        initCode: res.INIT_CODE,
        timeZone: commonParams.value?.TIME_ZONE,
      };
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/saveCodeSegment',
        method: 'post',
        params,
      });
      if (data.code === 200) {
        bus.emit('endCodeEvent');
        // , { success: true, code: 200, msg: '' }
        HModal.destroyAll();
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    };

    const getParentData = async () => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/queryParentCodeSegment',
        method: 'post',
        params: {
          codeSchemeId: props.componentProps?.params.codeSchemeId,
          objectId: props.componentProps?.params.objectID.EID,
          // pid:
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        parentDatas.length = 0;
        const pDatas = data.data.map(item => {
          return { label: item.name, value: item.id, level: item.level };
        });
        parentDatas.push(...pDatas);
      } else {
        message.error(data.msg);
      }
    };

    const getCodeRulesData = async (rule: string, isChange = true) => {
      thinDatas.length = 0;
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/queryCodeSegmentRules',
        method: 'get',
        params: {
          parentRule: rule,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      lengthDatas.length = 0;
      if (data.code === 200) {
        if (isChange || isChange === undefined) {
          model['FINE_RULES'] = undefined;
        }
        thinDatas.push(
          ...data.data.map(item => {
            return { label: item.key, value: item.value };
          }),
        );
      } else {
        message.error(data.msg);
      }
    };

    const getCodeDayData = async (date: string, isChange = true) => {
      nextTick(() => {
        formRef.value?.validateFields('INIT_CODE');
      });
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/queryLengthListByDate',
        method: 'get',
        params: {
          date,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (isChange) {
        model['LENGTH'] = undefined;
      }

      lengthDatas.length = 0;
      if (data.code === 200) {
        lengthDatas.push(
          ...data.data.map(item => {
            return { label: item.key, value: item.value };
          }),
        );
      } else {
        message.error(data.msg);
      }

      formMethods.updateSchema([
        {
          dataIndex: 'LENGTH',
          valueType: isDay ? 'Select' : 'Input',
          disabled: isEdit,
          fieldProps: {
            options: lengthDatas,
            onChange: changeLENGTH,
          },
          formItemProps: {},
        },
        {
          dataIndex: 'INIT_CODE',
          valueType: 'Input',
          renderFormItem: !baseHidden,
          dynamicRules: () => {
            //监听正则变化
            let pattern = '';
            if (model['LENGTH'] == 0) {
              pattern = '^' + model['FINE_RULES'] + '{0,20}$';
            } else if (model['LENGTH']) {
              pattern = '^' + model['FINE_RULES'] + '{0,' + model['LENGTH'] + '}$';
            } else {
              pattern =
                '^' +
                model['FINE_RULES'] +
                '{0,' +
                (model['LENGTH'] == 0 ? 20 : model['LENGTH']) +
                '}$';
            }
            console.log('pattern', pattern);

            return [
              {
                message: t('code.codeSegment.createOrEditCodeSegment.initCode'),
                pattern: pattern,
                trigger: 'change',
                required: false,
              },
            ];
          },
          formItemProps: {},
        },
      ]);
    };

    return {
      t,
      FormData,
      formProps,
      formRef,
      formMethods,
      model,
      selectUseClick,
      onFinish,
    };
  },
});
</script>
