<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 { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { BForm as HBForm } from '@crami/bui';
import { HModal, message } from '@crami/ui';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const formProps = {
  options: {
    type: Object,
  },
  data: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'CreateCodeSegment',
  props: formProps,
  components: {
    HBForm,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    let baseHidden = true;
    let isDay = false;
    const addCode = {
      pid: null,
      pname: null,
      level: '',
    };
    // 第二种方法，useForm调用查询方法
    const thinDatas = reactive([]);
    const lengthDatas = reactive([]);
    const parentDatas = reactive([]);
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        immediate: true,
        configApi: {
          // 测试使用admin接口，后续使用下面的
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            productLine:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.project
                : '',
            mode: 'add',
            name:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.modelName
                : '',
          },
          method: 'post',
        },
        saveApi:
          props.componentProps.params.saveDataParams?.saveUrl?.length != 'undefined'
            ? {
                url: props.componentProps?.params?.saveDataParams?.saveUrl,
                method: 'post',
                type: 'json',
              }
            : {},
        // 设置form的各种配置信息
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              // column: 2, // 一行展示几个
              isQuery: false,
              uniqueParams: uniqueParams(),
            };
            formMethods.setProps(_props, props);
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'ROUGH_RULES',
                  valueType: 'Select',
                  fieldProps: {
                    onSelect: selectUseClick,
                    onChange: onResetRoughRules,
                  },
                  width: baseHidden ? '50%' : '33%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'FINE_RULES',
                  valueType: 'Select',
                  fieldProps: {
                    options: thinDatas,
                    onSelect: selectFineClick,
                  },
                  width: baseHidden ? '50%' : '33%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'LENGTH',
                  valueType: 'Input',
                  fieldProps: {
                    onChange: changeLENGTH,
                  },
                },
                {
                  dataIndex: 'RESTART',
                  renderFormItem: !baseHidden,
                  fieldProps: {},
                  formItemProps: {},
                },
                {
                  dataIndex: 'INIT_CODE',
                  renderFormItem: !baseHidden,
                  fieldProps: {},
                  formItemProps: {},
                },

                {
                  dataIndex: 'PNAME',
                  valueType: 'Select',
                  fieldProps: {
                    options: parentDatas,
                    onChange: changePidClick,
                  },
                  formItemProps: {},
                },
              ],
              props,
            );
          }

          return props;
        },
      },
      undefined,
      emit,
      {
        isAdd: true,
        ...(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') },
      showActionButtonGroup: false,
      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: 'view',
        lang: commonParams.value?.lang,
      };
    };

    const changePidClick = (event: any) => {
      if (event === undefined) {
        addCode.pid = null;
        addCode.pname = null;
        addCode.level = null;
        return;
      }
      addCode.pid = event;
      for (let i = 0; i < parentDatas.length; i++) {
        const item = parentDatas[i];
        if (item.value === event) {
          addCode.pname = item.label;
          addCode.level = item.level;
          break;
        }
      }
    };
    const onResetRoughRules = e => {
      if (e === undefined) {
        model['FINE_RULES'] = undefined;
        model['INIT_CODE'] = '';
        baseHidden = true;
        thinDatas.length = 0;
        formMethods.updateSchema([
          {
            dataIndex: 'ROUGH_RULES',
            width: baseHidden ? '50%' : '33%',
          },
          {
            dataIndex: 'FINE_RULES',
            width: baseHidden ? '50%' : '33%',
            fieldProps: {
              options: thinDatas,
            },
          },
          {
            dataIndex: 'INIT_CODE',
            renderFormItem: !baseHidden,
          },
          {
            dataIndex: 'RESTART',
            renderFormItem: !baseHidden,
          },
        ]);
      }
    };
    const selectUseClick = (event: any) => {
      isDay = false;
      thinDatas.length = 0;
      if (event === 'PIPELINE_CODE') {
        baseHidden = false;
      } else if (event === 'DATE') {
        isDay = true;
        baseHidden = true;
        model['RESTART'] = '';
        model['INIT_CODE'] = '';
        model['LENGTH'] = undefined;
      } else {
        baseHidden = true;
        model['RESTART'] = '';
        model['INIT_CODE'] = '';
      }
      getCodeRulesData(event);
      formMethods.updateSchema(
        [
          {
            dataIndex: 'LENGTH',
            valueType: isDay ? 'Select' : 'Input',
            fieldProps: {
              options: lengthDatas,
            },
          },
          {
            dataIndex: 'ROUGH_RULES',
            valueType: 'Select',
            fieldProps: {
              onSelect: selectUseClick,
            },
            width: baseHidden ? '50%' : '33%',
            formItemProps: {},
          },
          {
            dataIndex: 'FINE_RULES',
            valueType: 'Select',
            fieldProps: {
              options: thinDatas,
            },
            width: baseHidden ? '50%' : '33%',
            formItemProps: {},
          },
          {
            dataIndex: 'RESTART',
            renderFormItem: !baseHidden,
            fieldProps: {},
            width: '33%',
            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']) +
                  '}$';
              }
              return [
                {
                  message: t('code.codeSegment.createOrEditCodeSegment.initCode'),
                  pattern: pattern,
                  trigger: 'change',
                  required: false,
                },
              ];
            },
            formItemProps: {},
          },
          {
            dataIndex: 'PNAME',
            valueType: 'Select',
            fieldProps: {
              options: parentDatas,
              onChange: changePidClick,
            },
            formItemProps: {},
          },
        ],
        props,
      );
    };

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

    const ok = () => {
      formMethods
        .validate()
        .then(res => {
          submitApi(res);
        })
        .catch(err => {
          console.info('---validate', err);
        });
    };

    const cancel = () => {
      emit('end', null);
    };

    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: addCode.pname,
        parentId: addCode.pid,
        level: addCode.level,
        restart: res.RESTART,
        describes: res.DESCRIBES,
        connect: commonParams.value?.connect,
        lang: commonParams.value?.lang,
        companyId: commonParams.value?.companyId,
        userId: commonParams.value?.user_id,
        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) {
        HModal.destroyAll();
        bus.emit('endCodeEvent');
        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,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
        },
      });
      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) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/queryCodeSegmentRules',
        method: 'get',
        params: {
          parentRule: rule,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
        },
      });
      lengthDatas.length = 0;
      if (data.code === 200) {
        model['FINE_RULES'] = undefined;
        thinDatas.length = 0;
        thinDatas.push(
          ...data.data.map(item => {
            return { label: item.key, value: item.value };
          }),
        );
      } else {
        message.error(data.msg);
      }
    };

    const getCodeDayData = async (date: string) => {
      nextTick(() => {
        formRef.value?.validateFields('INIT_CODE');
      });
      const datas = await useHttp({
        url: '/api/codemanagement/codeSegment/queryLengthListByDate',
        method: 'get',
        params: {
          date,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          userId: commonParams.value?.user_id,
        },
      });
      model['LENGTH'] = undefined;
      lengthDatas.length = 0;
      if (datas.code === 200) {
        lengthDatas.push(
          ...datas.data.map(item => {
            return { label: item.key, value: item.value };
          }),
        );
      } else {
        message.error(datas.msg);
      }
      formMethods.updateSchema([
        {
          dataIndex: 'LENGTH',
          valueType: isDay ? 'Select' : 'Input',
          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']) +
                '}$';
            }

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

    return {
      t,
      formRef,
      formProps,
      model,
      selectUseClick,
      ok,
      cancel,
      onResetRoughRules,
      changeLENGTH,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-form-vertical .ant-col) {
  margin-left: 0 !important;
}
</style>
