<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 { rtkAccountsaveOrEdit } from '/@/api/rtk/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import dayjs from 'dayjs';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({
        operator: '中国移动',
        ipAddr: '120.253.239.161',
        mountPoint: 'RTCM33_GRCEJ',
        port: '8001',
      });
      const fileFlow = reactive({
        file: null,
        title: '新增RTK账号',
      });
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
          colProps: {
            span: 20,
          },
        },
        {
          field: 'userName',
          component: 'Input',
          required: true,
          label: '用户名称',
          componentProps: {
            maxLength: 50,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'password',
          component: 'Input',
          label: '密码',
          required: true,
          componentProps: {
            maxLength: 50,
            'v-model:visible': false,
            // readonly:preventAutoFill.value,
            placeholder: '请输入数字、字母大小写组合',
          },
          colProps: { span: 20 },
        },
        {
          field: 'operator',
          component: 'Input',
          required: true,
          label: '运营商',
          defaultValue: '中国移动',
          componentProps: {
            maxLength: 50,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'ipAddr',
          component: 'Input',
          label: 'IP地址',
          ifShow: false,
          required: true,
          defaultValue: '120.253.239.161',
          colProps: {
            span: 20,
          },
          // rules: [
          //   {
          //     required: true,
          //     // @ts-ignore
          //     validator: async (rule, value) => {
          //       if (!value) {
          //         return Promise.reject('请输入IP地址');
          //       }
          //       if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
          //         /* eslint-disable-next-line */
          //         return Promise.reject('不支持中文字符');
          //       }
          //       return Promise.resolve();
          //     },
          //     trigger: 'change',
          //   },
          // ],
          componentProps: {
            maxLength: 50,
            onChange: (data) => {
              console.log('data', data);
            },
          },
        },
        {
          field: 'mountPoint',
          component: 'Input',
          required: true,
          label: '挂载点',
          defaultValue: 'RTCM33_GRCEJ',
          componentProps: {
            maxLength: 50,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'port',
          component: 'Input',
          required: true,
          label: '端口',
          defaultValue: '8001',
          componentProps: {
            maxLength: 50,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'failureTime',
          component: 'DatePicker',
          label: '到期日期',
          colProps: {
            span: 16,
          },
          componentProps: {
            // disabled: true,
            valueFormat: 'YYYY-MM-DD',
            format: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return current && current < dayjs().endOf('day');
            },
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema, clearValidate }] =
        useForm({
          labelWidth: 120,
          schemas,
          showActionButtonGroup: false,
          actionColOptions: {
            span: 20,
          },
        });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        modelRef.value = data;
        fileFlow.title = data.id ? '编辑账号' : '新增账号';
        // handlertkSn(data.cameraSnCode ? true : false);
        resetFields();
        console.log('data', data);
        handlertkType(data.rtkType);
        setFieldsValue(data);
        clearValidate();
      }
      function handlertkType(val) {
        console.log('val', val);
        let ifShow = val != 0;
        updateSchema([
          { field: 'ipAddr', ifShow },
          { field: 'mountPoint', ifShow },
          { field: 'port', ifShow },
          { field: 'userName', ifShow },
          // { field: 'sgRtkSn', ifShow },
          { field: 'password', ifShow },
          { field: 'operator', ifShow },
        ]);
      }
      function handlertkSn(val) {
        console.log('handlertkSn', val);
        let required = !!val;
        !required && clearValidate();
        updateSchema([
          { field: 'cameraSnCode', required },
          { field: 'rtkType', required },
          {
            field: 'rtkSnCode',
            rules: [
              {
                required: required,
                // @ts-ignore
                validator: (rule, value, callback) => {
                  function isSpec(s) {
                    var pattern = /[~!@#$%^&*<>|']/gi;
                    return pattern.test(s);
                  }
                  if(required && !value){
                    return Promise.reject('请输入板卡SN号');
                  }
                  if (value != null && value !== '') {
                    if (isSpec(value) || value.indexOf(' ') !== -1) {
                      return Promise.reject('不能包含特殊字符或空格');
                    } else {
                      return Promise.resolve();
                    }
                  } else {
                    return Promise.resolve();
                  }
                },
                trigger: 'change',
              },
            ],
          },
          // { 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 rtkAccountsaveOrEdit(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>
