<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="fileFlow.title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadApi } from '/@/api/product/index';
  import { rtkaccountFormSchema } from './data';
  import { rtkDevicesaveOrEdit } from '/@/api/rtk/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const userStore = useUserStore();
      const iseur = userStore.isEnv;
      const modelRef = ref({
        operator: '中国移动',
        ipAddr: '120.253.239.161',
        mountPoint: 'RTCM33_GRCEJ',
        port: '8001',
      });
      const fileFlow = reactive({
        file: null,
        title: '新增RTK账号',
      });
      let disabledDate = (current: any) => {
        return current && current < moment().subtract(1, 'days').endOf('day');
      };
      let range = (start: any, end: any) => {
        const result = [];
        for (let i = start; i < end; i++) {
          result.push(i);
        }
        return result;
      };
      let disabledDateTime = (current: any) => {
        if (current) {
          let today = moment().date();
          if (today == current.date()) {
            let minute = Number(moment().minutes());
            let hour = Number(moment().hour());
            let finalHour: number, finalMinute: number;
            console.log('today', minute, current.hour(), hour);
            // if (current.hour() > hour) {
            //   finalMinute = 0;
            // } else {
            if (current.minute() >= 58) {
              finalHour = hour + 1;
              finalMinute = 0;
            } else {
              finalHour = hour;
              finalMinute = minute + 5;
            }
            // }
            console.log('today', finalHour, finalMinute);
            return {
              disabledHours: () => range(0, finalHour),
              disabledMinutes: () => range(0, finalMinute),
            };
          } else if (moment() > current) {
            return {
              disabledHours: () => range(0, 24),
              disabledMinutes: () => range(0, 60),
              disabledSeconds: () => range(0, 60),
            };
          }
        } else {
          return {
            disabledHours: () => range(0, 24),
            disabledMinutes: () => range(0, 60),
            disabledSeconds: () => range(0, 60),
          };
        }
      };
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
          colProps: {
            span: 18,
          },
        },
        {
          field: 'cameraType',
          component: 'Select',
          label: '设备类型',
          required: true,
          defaultValue: 1,
          colProps: {
            span: 18,
          },
          componentProps: {
            options: [
              {
                label: '四维看见',
                value: 1,
                key: 1,
              },
              {
                label: '四维深时',
                value: 2,
                key: 2,
              },
              {
                label: '四维深光',
                value: 3,
                key: 3,
              },
            ],
            onChange: (value) => {
              handleCarmanType(value);
            },
          },
          // required: true,
        },
        {
          field: 'cameraSn',
          component: 'Input',
          required: true,
          label: '相机sn',
          componentProps: {
            maxLength: 50,
            onChange: (value) => {
              // handlertkSn(value.target.value);
            },
          },
          colProps: {
            span: 18,
          },
        },
        {
          field: 'rtkType',
          component: 'Select',
          label: '板卡类型',
          required: true,
          colProps: {
            span: 18,
          },
          componentProps: {
            options: [
              {
                label: '千寻板卡',
                value: 1,
                key: 1,
              },
              {
                label: '北云板卡',
                value: 2,
                key: 2,
              },
            ],
            onChange: (value) => {
              // if(value == 0){
              //   handlertkuserType(1);
              // }
              handlertkType(value);
            },
          },
          // required: true,
        },
        {
          field: 'rtkSnCode',
          component: 'Input',
          required: true,
          label: '板卡SN号',
          componentProps: {
            maxLength: 50,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: (rule, value) => {
                function isSpec(s) {
                  var pattern = /[~!@#$%^&*<>|']/gi;
                  return pattern.test(s);
                }
                if (value != null && value !== '') {
                  if (isSpec(value) || value.indexOf(' ') !== -1) {
                    return Promise.reject('不能包含特殊字符或空格');
                  } else {
                    return Promise.resolve();
                  }
                } else {
                  return Promise.reject('不能为空');
                }
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 18,
          },
        },
        {
          field: 'sgRtkSn',
          component: 'Input',
          required: true,
          label: '深光rtk插件SN号',
          ifShow: false,
          componentProps: {
            maxLength: 50,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: (rule, value) => {
                console.log('isValidateTxtNonSpec', value);
                function isSpec(s) {
                  var pattern = /[~!@#$%^&*<>|']/gi;
                  return pattern.test(s);
                }
                if (!value) {
                  return Promise.reject('请输入深光rtk插件SN号');
                }
                if (value != null && value !== '') {
                  if (isSpec(value) || value.indexOf(' ') !== -1) {
                    return Promise.reject('不能包含特殊字符或空格');
                  } else {
                    return Promise.resolve();
                  }
                } else {
                  return Promise.resolve();
                }
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 18,
          },
        },
        {
          field: 'accountType',
          component: 'Select',
          label: '账号类型',
          required: true,
          colProps: {
            span: 18,
          },
          componentProps: {
            options: [
              {
                label: '账号池（不限期）',
                value: 0,
                key: 0,
              },
              {
                label: '账号池（限期）',
                value: 2,
                key: 2,
              },
              {
                label: '专用账号',
                value: 1,
                key: 1,
              },
            ],
            onChange: (value) => {
              handlertkuserType(value);
            },
          },
          // required: true,
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema, clearValidate }] =
        useForm({
          labelWidth: 120,
          schemas: [
            ...schemas,
            ...rtkaccountFormSchema,
            {
              field: 'failureTime',
              component: 'DatePicker',
              label: '到期日期',
              ifShow: false,
              colProps: {
                span: 16,
              },
              componentProps: {
                disabledDate: disabledDate,
                disabledTime: disabledDateTime,
                showTime: { defaultValue: moment('23:59:59', 'HH:mm:ss') },
                valueFormat: 'YYYY-MM-DD HH:mm:ss',

                // defaultValue: dayjs().add(7, 'day').format('YYYY-MM-DD') + ' 23:59:59',
                format: 'YYYY-MM-DD HH:mm:ss',
              },
            },
          ],
          showActionButtonGroup: false,
          actionColOptions: {
            span: 18,
          },
        });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      let tg = false
      function onDataReceive(data) {
        modelRef.value = data;
        fileFlow.title = data.id ? '编辑RTK' : '新增RTK';
        // handlertkSn(data.cameraSn ? true : false);
        resetFields();
        console.log('data', data);
        tg = data.rtkType != 0 && data.accountType == 1 ? true : false
        handleCarmanType(data.cameraType != null ? data.cameraType : 1);
        handlertkType(data.rtkType != null ? data.rtkType : 1);
        data.rtkType != 0 && handlertkuserType(data.accountType != null ? data.accountType : 0);
        setFieldsValue(data);
        clearValidate();
      }
      function handlertkType(val) {
        console.log('handlertkType', val);
        let upload = [
          { field: 'accountType', ifShow: val != 0 },
          { field: 'failureTime', ifShow: val == 0 },
        ]
        setFieldsValue({
          accountType: null
        })
        let ifShow = tg || false
        // let ifShow = false
        upload.push(
          ...[
          { field: 'ipAddr', ifShow },
          { field: 'mountPoint', ifShow },
          { field: 'port', ifShow },
          { field: 'userName', ifShow },
          { field: 'password', ifShow },
          { field: 'operator', ifShow },
      ]
        )
        updateSchema(upload);
        tg = false
      }
      function handlertkuserType(val) {
        console.log('handlertkuserType', val);
        let ifShow = val == 1;
        updateSchema([
          { field: 'ipAddr', ifShow },
          { field: 'mountPoint', ifShow },
          { field: 'port', ifShow },
          { field: 'userName', ifShow },
          // { field: 'sgRtkSn', ifShow },
          // { field: 'failureTime', ifShow: val == 0 && !iseur },
          { field: 'password', ifShow },
          { field: 'operator', ifShow },
          { field: 'failureTime', ifShow },
        ]);
      }
      function handleCarmanType(val) {
        let ifShow = val == 3;
        updateSchema([
          { field: 'sgRtkSn', ifShow },
          { field: 'cameraSn', required: val != 3 },
        ]);
      }
      function handlertkSn(val) {
        console.log('handlertkSn', val);
        let required = !!val;
        !required && clearValidate();
        updateSchema([
          { field: 'cameraSn', required },
          // { field: 'rtkType', required },
          { field: 'sgRtkSn', required },
          { field: 'ipAddr', required },
          { field: 'mountPoint', required },
          { field: 'port', required },
          { field: 'userName', required },
          { field: 'password', required },
          { field: 'operator', required },
        ]);
      }

      const handleSubmit = async () => {
        function isEmptyString(value) {
          return value === null || value === undefined || value === '';
        }
        try {
          const params = await validate();
          let keyData = Object.values(params).some((item) => {
            if (item == params.id) {
              return false;
            } else {
              return !isEmptyString(item);
            }
          });
          if (!keyData) {
            return createMessage.error('请填写至少一项数据');
          }
          params.rtkSnCode = params.rtkSnCode && params.rtkSnCode.trim();
          console.log('params', Object.values(params), keyData);
          const res = await rtkDevicesaveOrEdit(params);
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        handlertkSn,
        t,
      };
    },
  });
</script>
