<template>
  <h-b-form class="create-codeProgram" ref="formRef" name="use" v-bind="formProps" :model="model">
    <template #STREAMING_CODE>
      <h-radio-group 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 { computed, defineComponent, reactive, ref } 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 {
  RadioGroup as HRadioGroup,
  Radio as HRadio,
  ToolTip as HToolTip,
  HModal,
  message,
} from '@crami/ui';
import type { IModalPageParams } from '@crami/ui-types';
import SelectCodeUseObject from './SelectCodeUseObject.vue';
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 formProps = {
  options: {
    type: Object,
  },
  data: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
  value: {
    type: String,
  },
};

export default defineComponent({
  name: 'CreateCodeProgram',
  props: formProps,
  components: {
    HRadio,
    HRadioGroup,
    HToolTip,
    InfoCircleOutlined,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    // 计算studio是否配置弹窗按钮
    const isStudioButton = computed(() => {
      const paramsKeys = Object.keys(props.componentProps?.params); //取出配置信息key
      return paramsKeys.includes('okText') && paramsKeys.includes('cancelText');
    });
    const useObjs = ref([]);
    const createProps = ref();
    const streamRadioValue = ref();
    // 第二种方法，useForm调用查询方法
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        immediate: true,
        configApi: {
          // 测试使用admin接口，后续使用下面的
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...props.componentProps?.params,
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form',
            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') {
            for (let i = 0; i < props.schemas.length; i++) {
              const item = props.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;
              }
              model['USE_OBJECT_DISPLAYVALUE'] = [];
            }
            const _props: any = {
              // column: 2, // 一行展示几个
              isQuery: false,
              uniqueParams: uniqueParams(),
              submitter: {
                showActionButtonGroup: false,
                isQuery: false, // 是否为查询表单
              },
            };
            formMethods.setProps(_props, props);
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'ENAME',
                  fieldProps: {},
                  width: '50%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'STATEID',
                  width: '50%',
                  formItemProps: {},
                },
                {
                  dataIndex: 'OICODE',
                  width: '50%',
                  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',
                  title: t('code.codeProgramme.createOrEditCodePro.useObjTitle'),
                  valueType: 'Input',
                  fieldProps: {},
                  width: '100%',
                  formItemProps: {
                    hidden: true,
                  },
                },
              ],
              props,
            );
          }

          return props;
        },
        beforeRequest: (type, params: any) => {
          const tempParams = { ...params };
          if (type === 'save') {
            tempParams.data.USE_OBJECT_DISPLAYVALUE = useObjs.value
              .map(item => item.label)
              .join(',');
          }
          return {
            ...tempParams,
          };
        },
      },
      undefined,
      emit,
      {
        isAdd: true,
        ...(props.componentProps?.params || {}),
      },
    );

    const submitter = reactive({
      showActionButtonGroup: !isStudioButton.value,
      isQuery: false, // 是否为查询表单
      submitOnReset: false,
      searchConfig: { resetText: t('code.common.cancel') },
      onReset: () => {
        formMethods.clearValidate();
        emit('end');
      },
    });
    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 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 ok = () => {
      formMethods
        .validate()
        .then(res => {
          submitApi(res);
        })
        .catch(err => {
          console.info('---validate', err);
        });
    };

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

    const submitApi = async (res: any) => {
      const params = {
        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,
      formRef,
      formProps,
      model,
      useObjs,
      selectUseClick,
      deSelectUseClick,
      streamRadioValue,
      createProps,
      radioChange,
      ok,
      cancel,
    };
  },
});
</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>
