<template>
  <h-b-form ref="formRef" name="use" v-bind="formProps" :model="model">
    <template #STREAMING_CODE>
      <h-radio-group
        :disabled="isEdit"
        v-model:value="streamRadioValue"
        name="STREAMING_CODE"
        @change="radioChange"
      >
        <h-radio v-for="item in createProps" :value="item.value" :key="item.value">
          {{ item.label }}
          <h-tool-tip :title="item.tip">
            <info-circle-outlined class="stream_radio" />
          </h-tool-tip>
        </h-radio>
      </h-radio-group>
    </template>
  </h-b-form>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, toRef } from 'vue';
import { useForm } from '@crami/bui-platform';
import { BForm as HBForm } from '@crami/bui';
import {
  RadioGroup as HRadioGroup,
  Radio as HRadio,
  ToolTip as HToolTip,
  HModal,
  message,
} from '@crami/ui';
import SelectCodeUseObject from './SelectCodeUseObject.vue';
import type { IModalPageParams } from '@crami/ui-types';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const props = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'EditCodeProgram',
  props: props,
  components: {
    HBForm,
    HRadio,
    HRadioGroup,
    HToolTip,
    InfoCircleOutlined,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const useObjs = ref([]);
    const isEdit = toRef(props.componentProps?.params, 'isEdit');
    const createProps = ref();
    const streamRadioValue = ref();
    // 第二种方法，useForm调用查询方法
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form',
            productLine: commonParams.value?.project,
            mode: 'edit',
            name: 'P_SYS_CODE_SCHEME',
          },
          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,
            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') {
            const titles = prop.USE_OBJECT_DISPLAYVALUE
              ? prop.USE_OBJECT_DISPLAYVALUE.split(',')
              : [];
            useObjs.value = [];
            const values = prop.USE_OBJECT ? prop.USE_OBJECT.split(',') : [];
            for (let i = 0; i < titles.length; i++) {
              useObjs.value.push({ label: titles[i], value: values[i] });
            }
            streamRadioValue.value = prop.STREAMING_CODE;
            Object.assign(model, prop);
            model['USE_OBJECT_DISPLAYVALUE'] = values;
          }
          if (type === 'config') {
            for (let i = 0; i < prop.schemas.length; i++) {
              const item = prop.schemas[i];
              if (item.dataIndex === 'STREAMING_CODE' && item.dataSource) {
                createProps.value = item.dataSource.map(item => {
                  let tip = '';
                  if (item.value === 'GREAT_FLOWING_WATER') {
                    tip = t('code.codeProgramme.createOrEditCodePro.flowWaterTip');
                  } else if (item.value === 'BRANCH_FLOW') {
                    tip = t('code.codeProgramme.createOrEditCodePro.branchFlowTip');
                  }
                  return { ...item, tip };
                });
                break;
              }
            }
            const _props: any = {
              isQuery: false,
              uniqueParams: uniqueParams(),
              submitter: {
                showActionButtonGroup: false,
                isQuery: false,
              },
            };
            formMethods.setProps(_props, prop);
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'ENAME',
                  fieldProps: {
                    disabled: isEdit,
                  },
                  width: '50%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'STATEID',
                  width: '50%',
                  disabled: true,
                  fieldProps: {},
                  formItemProps: {},
                },
                {
                  dataIndex: 'OICODE',
                  width: '50%',
                  fieldProps: {
                    disabled: isEdit,
                  },
                  formItemProps: {},
                },
                {
                  dataIndex: 'STREAMING_CODE',
                  width: '50%',
                  formItemProps: {},
                  slot: 'STREAMING_CODE',
                },
                {
                  dataIndex: 'USE_OBJECT_DISPLAYVALUE',
                  valueType: 'Select',
                  title: t('code.codeProgramme.createOrEditCodePro.useObjTitle'),
                  fieldProps: {
                    open: false,
                    mode: 'tags',
                    showArrow: true,
                    options: useObjs,
                    onClick: selectUseClick,
                    onChange: deSelectUseClick,
                  },
                  width: '100%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'USE_OBJECT',
                  valueType: 'Input',
                  fieldProps: {},
                  width: '100%',
                  formItemProps: {
                    hidden: true,
                  },
                },
              ],
              prop,
            );
          }

          return prop;
        },
        beforeRequest: (type, params: any) => {
          const tempParams = { ...params };
          if (type === 'save') {
            tempParams.data.USE_OBJECT_DISPLAYVALUE = useObjs.value
              .map(item => item.label)
              .join(',');
          }
          return {
            ...tempParams,
          };
        },
        afterRequest: (type, prop) => {
          if (type === 'save') {
            bus.emit('endCodeEvent');
            HModal.destroyAll();
          }
          return prop;
        },

        immediate: true,
      },
      undefined,
      emit,
      {
        isAdd: false,
        ...(props.componentProps?.params || {}),
      },
    );

    const submitter = reactive({
      isQuery: false, // 是否为查询表单
      submitOnReset: false,
      searchConfig: { resetText: t('code.common.cancel') },
      onReset: () => {
        formMethods.clearValidate();
        HModal.destroyAll();
      },
    });
    formProps.submitter = submitter;

    const model = reactive({});

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

    const componentRef = ref();
    const selectUseClick = () => {
      let options = reactive<IModalPageParams>({
        title: t('code.codeProgramme.createOrEditCodePro.selectUseObjTitle'),
        content: SelectCodeUseObject,
        componentProps: { keys: useObjs.value.map(item => item.value), instanceRef: componentRef },
        // 点击确定按钮的回调
        onOk: () => {
          useObjs.value = [];
          for (let i = 0; i < componentRef.value.targetKeys.length; i++) {
            const key = componentRef.value.targetKeys[i];
            for (let j = 0; j < componentRef.value.dataSource.length; j++) {
              const item = componentRef.value.dataSource[j];
              if (item.key === key) {
                useObjs.value.push({ label: item.title, value: key });
              }
            }
          }
          model['USE_OBJECT'] = useObjs.value.map(item => item.value).join(',');
          model['USE_OBJECT_DISPLAYVALUE'] = useObjs.value.map(item => item.value);
          formMethods.validateFields('USE_OBJECT_DISPLAYVALUE');
        },
        onCancel: () => {},
        width: 886,
      });
      HModal.page(options);
    };

    const deSelectUseClick = (event: any) => {
      if (event.length === 0) {
        useObjs.value = [];
        model['USE_OBJECT'] = useObjs.value.map(item => item.value).join(',');
        return;
      }
      useObjs.value = [].concat(
        useObjs.value.filter(item => {
          return event.includes(item.value);
        }),
      );
      model['USE_OBJECT'] = useObjs.value.map(item => item.value).join(',');
    };

    const radioChange = () => {
      model['STREAMING_CODE'] = streamRadioValue.value;
    };

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

    const submitApi = async (res: any) => {
      const params = {
        objectId: props.componentProps?.params?.objectID,
        stateID: res.STATEID,
        oiCode: res.OICODE,
        streamingCode: res.STREAMING_CODE,
        codeSchemeName: res.ENAME,
        describes: res.DESCRIBES,
        useObjectDisplayValue: useObjs.value.map(item => item.label).join(','),
        useObject: useObjs.value.map(item => item.value).join(','),
        connect: commonParams.value?.connect,
        lang: commonParams.value?.lang,
        companyId: commonParams.value?.companyId,
        userId: commonParams.value?.user_id,
        userGroup: commonParams.value?.userGroup,
        timeZone: commonParams.value?.TIME_ZONE,
      };
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/saveCodeScheme',
        method: 'post',
        params,
      });
      if (data.code === 200) {
        HModal.destroyAll();
        bus.emit('endCodeEvent');
        message.success(data.msg);
      } else {
        message.error(data.msg);
      }
    };

    return {
      t,
      FormData,
      formProps,
      formRef,
      formMethods,
      model,
      isEdit,
      selectUseClick,
      streamRadioValue,
      createProps,
      radioChange,
      onFinish,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-form-vertical .ant-col) {
  margin-left: 0 !important;
}
.stream_radio {
  color: #999999;
  margin-left: 3px;
  vertical-align: middle;
}
.stream_radio:hover {
  color: #3979f9;
}
</style>
