<template>
  <BasicModal
    @register="register"
    :title="tabType == 'deviceInfo' ? '设备编辑' : '报表录入'"
    width="1000px"
    v-bind="$attrs"
    @ok="onSubmit"
    :mask-closable="false"
  >
    <BasicForm ref="FormRef" @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { onMounted, ref, defineEmits, onUnmounted, watch, computed } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { FormSchema } from '/@/components/Form';
import { getFormSchemaColumns } from '/@/hooks/web/useWebColumns';
import { list as substationList } from '/@/views/vent/deviceManager/substationTabel/substation.api';
import { getRegulation as getRegulationList } from '/@/views/vent/deviceManager/substationTabel/substation.api';
import { list, updateDeviceInfo, updateReportInfo } from '../comment.api';
import { getAutoScrollContainer } from '/@/utils/common/compUtils';

const emit = defineEmits(['close', 'register']);
const props = defineProps({
  // formSchema: {
  //   type: Array as PropType<FormSchema[]>,
  //   default: () => [],
  // },
  deviceType: {
    type: String,
    default: '',
  },
});
const FormRef = ref();
const tabType = ref('deviceInfo');
const formSchema = ref<Array<FormSchema>>([]);
const formData = ref({});
// const props.deviceType ref('');
const deviceType = computed(() => props.deviceType);

// const arrToFormColumns = (tableHeaderColumns = [], devicetype) => {
//   const columnList: any[] = [];
//   tableHeaderColumns.forEach((item: any) => {
//     let columnsItem;
//     if (item.type == 1 || item.type == 10) {
//       columnsItem = {
//         label: item.des, //_dictText
//         field: item.monitorcode,
//         component: item.type == 1 ? 'Input' : item.type == 10 ? 'InputTextArea' : '',
//       };
//     } else {
//       if (item.type == 2 && item['monitorcode'] == 'nsubstationid') {
//         columnsItem = {
//           label: item.des, //_dictText
//           field: item.monitorcode,
//           component: 'ApiSelect',
//           componentProps: {
//             api: substationList,
//             labelField: 'strname',
//             valueField: 'id',
//           },
//         };
//       }
//       if (item.type == 3) {
//         columnsItem = {
//           label: item.des, //_dictText
//           field: item.monitorcode,
//           component: 'RadioGroup',
//           defaultValue: 1,
//           componentProps: () => {
//             return {
//               options: [
//                 { label: '是', value: 1, key: '1' },
//                 { label: '否', value: 0, key: '2' },
//               ],
//               stringToNumber: true,
//             };
//           },
//         };
//       }
//       if (item.type == 4) {
//         columnsItem = {
//           label: item.des, //_dictText
//           field: item.monitorcode,
//           component: 'JDictSelectTag',
//           componentProps: {
//             dictCode: item.dict,
//             placeholder: '请选择',
//             stringToNumber: true,
//           },
//         };
//       }
//     }
//     columnList.push(columnsItem);
//   });
//   formSchema.value = columnList
//   if(tabType.value === 'deviceInfo'){
//     formSchema.value.unshift(
//       {
//         label: '设备id', //_dictText
//         field: 'id',
//         component: 'Input',
//         componentProps: {
//           disabled: true,
//           show: false
//         },
//       },
//       {
//         label: '点表',
//         field: 'strtype',
//         component: 'JDictSelectTag',
//         componentProps: {
//           dictCode: `${devicetype.split('_')[0]}kind`,
//           placeholder: '请选择点表',
//         },
//       })
//       formSchema.value.push(
//       {
//         label: '备用分站',
//         field: 'stationids',
//         component: 'ApiSelect',
//         componentProps: {
//           api: substationList,
//           labelField: 'strname',
//           valueField: 'id',
//         },
//       },
//     )
//   }else{
//     formSchema.value.unshift(
//       {
//         label: '设备id', //_dictText
//         field: 'id',
//         component: 'Input',
//         componentProps: {
//           disabled: true,
//           show: false
//         },
//       })
//   }
// };

const arrToFormColumns = (tableHeaderColumns = []) => {
  const columnList: any[] = [];
  console.log(tableHeaderColumns, 'tableHeaderColumns');
  tableHeaderColumns.forEach((item: any) => {
    let columnsItem;
    if (item.type == 1 || item.type == 10) {
      columnsItem = {
        label: item.des, //_dictText
        field: item.monitorcode,
        component: item.type == 1 ? 'Input' : item.type == 10 ? 'InputTextArea' : '',
      };
    } else {
      if (item.type == 2 && item['monitorcode'] == 'nsubstationid') {
        columnsItem = {
          label: item.des, //_dictText
          field: item.monitorcode,
          component: 'ApiSelect',
          componentProps: {
            api: substationList,
            labelField: 'strname',
            valueField: 'id',
          },
        };
      }
      if (item.type == 3) {
        columnsItem = {
          label: item.des, //_dictText
          field: item.monitorcode,
          component: 'RadioGroup',
          defaultValue: 1,
          componentProps: () => {
            return {
              options: [
                { label: '是', value: 1, key: '1' },
                { label: '否', value: 0, key: '2' },
              ],
              stringToNumber: true,
            };
          },
        };
      }
      if (item.type == 4) {
        columnsItem = {
          label: item.des, //_dictText
          field: item.monitorcode,
          component: 'JDictSelectTag',
          componentProps: {
            dictCode: item.dict,
            placeholder: '请选择',
            // stringToNumber: true,
          },
        };
      }
      // date日期
      if (item.type == 8) {
        columnsItem = {
          label: item.des, //_dictText
          field: item.monitorcode,
          component: 'DatePicker',
          componentProps: {
            showTime: false,
            valueFormat: 'YYYY-MM-DD',
            getPopupContainer: getAutoScrollContainer,
          },
        };
      }
      // 日期+时间
      if (item.type == 9) {
        columnsItem = {
          label: item.des, //_dictText
          field: item.monitorcode,
          component: 'DatePicker',
          componentProps: {
            showTime: true,
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            getPopupContainer: getAutoScrollContainer,
          },
        };
      }
    }
    columnList.push(columnsItem);
  });
  formSchema.value = columnList;
  formSchema.value.unshift(
    {
      label: '设备id', //_dictText
      field: 'id',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '点表',
      field: 'strtype',
      component: 'JDictSelectTag',
      componentProps: {
        dictCode: `${deviceType.value.split('_')[0]}kind`, //${deviceType.value}kind
        placeholder: '请选择点表',
        // stringToNumber: true,
      },
    },
    {
      label: '规程值',
      field: 'regulation',
      component: 'ApiSelect',
      componentProps: {
        api: getRegulationList,
        labelField: 'name',
        valueField: 'id',
      },
    }
  );
  formSchema.value.push(
    {
      label: '备用分站',
      field: 'stationids',
      component: 'ApiSelect',
      componentProps: {
        api: substationList,
        labelField: 'strname',
        valueField: 'id',
      },
    },
    {
      label: '是否显示',
      field: 'linkId',
      component: 'RadioGroup',
      defaultValue: 1,
      componentProps: () => {
        return {
          options: [
            { label: '是', value: 1, key: '1' },
            { label: '否', value: 0, key: '2' },
          ],
          stringToNumber: true,
        };
      },
    }
  );
};
// 注册 modal
const [register, { closeModal, setModalProps }] = useModalInner(async (data) => {
  tabType.value = data.type;
  const deviceId = data.deviceId;
  if (FormRef.value) {
    setModalProps({ confirmLoading: false });
    getColumns();
    resetSchema(formSchema.value);
    resetFields();
    const result = await list({ id: deviceId });
    formData.value = result['records'][0];
    await setFieldsValue({
      ...formData.value,
    });
  }
});

const [registerForm, { resetSchema, getFieldsValue, setFieldsValue, resetFields }] = useForm({
  schemas: formSchema.value,
  showActionButtonGroup: false,
});

function getColumns() {
  let formSchemaArr = getFormSchemaColumns(tabType.value === 'deviceInfo' ? `${props.deviceType}_edit` : `${props.deviceType}_input`) || [];
  if (formSchemaArr && formSchemaArr.length < 1) {
    const arr = props.deviceType.split('_');
    formSchemaArr = getFormSchemaColumns(tabType.value === 'deviceInfo' ? arr[0] + '_edit' : arr[0] + '_input') || [];
  }
  arrToFormColumns(formSchemaArr);
}

watch(
  () => props.deviceType,
  () => {
    getColumns();
    if (FormRef.value) resetSchema(formSchema.value);
  }
);

async function onSubmit() {
  let formValue = getFieldsValue();
  setModalProps({ confirmLoading: true });
  if (tabType.value === 'deviceInfo') {
    await updateDeviceInfo(formValue);
  } else {
    await updateReportInfo(formValue);
  }

  setModalProps({ confirmLoading: false });
  emit('close');
  closeModal();
}

onMounted(async () => {});
onUnmounted(() => {});
</script>
<style scoped lang="less">
@import '/@/design/theme.less';
@import '/@/design/vent/modal.less';
</style>
