<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 { rtkDevicesaveOrEdit } from '/@/api/rtk/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  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: 'cameraSn',
          component: 'Input',
          required: true,
          label: '相机sn',
          componentProps: {
            maxLength: 50,
            onChange: (value) => {
              handlertkSn(value.target.value);
            },
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'rtkType',
          component: 'Select',
          label: '板卡类型',
          required: true,
          colProps: {
            span: 18,
          },
          componentProps: {
            options: [
              {
                label: '千寻板卡千寻账号',
                value: 0,
                key: 0,
              },
              {
                label: '千寻板卡移动账号',
                value: 1,
                key: 1,
              },
              {
                label: '北云板卡移动账号',
                value: 2,
                key: 2,
              },
            ],
            onChange: (value) => {
              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: 20,
          },
        },
        {
          field: 'sgRtkSn',
          component: 'Input',
          required: false,
          label: '深光rtk插件SN号',
          componentProps: {
            maxLength: 50,
          },
          rules: [
            {
              required: false,
              // @ts-ignore
              validator: (rule, value) => {
                console.log('isValidateTxtNonSpec', 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.resolve();
                }
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 20,
          },
        },
      ];
      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 ? '编辑RTK' : '新增RTK';
        handlertkSn(data.cameraSn ? 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: '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>
