<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.rightsEnterprises.add')"
    @ok="saveTable"
    width="700px"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <div class="table_list">
        <BasicTable @register="registerSubtable">
          <template #time>
            <Time :value="new Date()" mode="date" />
          </template>
        </BasicTable>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Time } from '/@/components/Time';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { allListType, saveRights } from '/@/api/rightsEnterprises/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      BasicTable,
      Time,
    },
    props: {
      userData: { type: Object },
    },
    emits: ['addtable', 'register', 'update'],
    setup(props, { emit }) {
      const { t } = useI18n();
      const { createConfirm, createMessage } = useMessage();

      const [registerModal, { openModal: addopenModal }] = useModal();
      const minNumber = reactive({
        shotNum: 0,
        lookNum: 0,
      });
      const modelRef = reactive({
        id: 0,
        subNum: 0,
        companyId: 0,
      });
      const columns: BasicColumn[] = [
        {
          title: t('routes.rightsEnterprises.rightsType'),
          width: 0,
          ifShow: false,
          dataIndex: 'id',
        },
        {
          title: t('routes.rightsEnterprises.rightsType'),
          width: 160,
          dataIndex: 'permType',
        },
        {
          title: t('routes.rightsEnterprises.year'),
          width: 80,
          dataIndex: 'useYear',
        },
        {
          title: t('routes.rightsEnterprises.muber'),
          dataIndex: 'muber',
          edit: true,
          // slots: { customRender: 'subNum' },
          editRule: async (text) => {
            var regPos = /^[0-9]\d*$/; // 整数
            if (text > 999 || text < -1) {
              return t('routes.rightsEnterprises.maxlength');
            } else if (!regPos.test(text)) {
              return t('routes.rightsEnterprises.integer');
            }
            return '';
          },
          editComponent: 'InputNumber',
          width: 200,
        },
        {
          title: t('routes.rightsEnterprises.purchaseTime'),
          width: 150,
          dataIndex: 'purchaseTime',
          slots: { customRender: 'time' },
        },
      ];
      const schemas: FormSchema[] = [
        {
          field: 'companyPhone',
          component: 'Input',
          label: `${t('routes.corporation.enterpriseId')} ：`,
          slot: 'text',
          labelWidth: 200,
        },
        {
          field: 'companyName',
          label: `${t('routes.corporation.enterpriseName')} ：`,
          slot: 'text',
          component: 'Input',
          labelWidth: 200,
        },
      ];
      const [registerForm, { setFieldsValue, resetFields, getFieldsValue, validateFields }] =
        useForm({
          labelWidth: 120,
          schemas,
          showActionButtonGroup: false,
          actionColOptions: {
            span: 24,
          },
        });

      const [
        registerSubtable,
        { reload: reloadSubtable, deleteTableDataRecord, getDataSource, insertTableDataRecord },
      ] = useTable({
        // title: `${t('routes.devices.listTile')}`,
        rowKey: 'phone',
        api: allListType,
        showIndexColumn: false,
        canResize: false,
        afterFetch: (T) => {
          console.log('afterFetch', T);
          return T.map((ele) => {
            ele.muber = 1;
            return ele;
          });
        },
        columns,
        bordered: true,
        pagination: false,
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(unref(data));
      });

      async function onDataReceive(data) {
        console.log('Data Received', data);
        // 方式1;
        resetFields();
        reloadSubtable();
        modelRef.companyId = data.companyId;
        setFieldsValue({
          ...data,
        });
      }
      async function numOnChange() {
        // await setFieldsValue({
        //   [name]: data,
        // });
        let { shotNum, lookNum } = getFieldsValue();
        modelRef.subNum = lookNum + shotNum;
        validateFields(['lookNum', 'shotNum']);
      }
      async function numsOnChange(data, type) {
        let formdata = getFieldsValue();
        let value = formdata[type];
        if (data) {
          value++;
        } else {
          value--;
        }
        await setFieldsValue({
          [type]: value,
        });
        let { shotNum, lookNum } = getFieldsValue();
        modelRef.subNum = lookNum + shotNum;
        validateFields(['lookNum', 'shotNum']);
      }
      async function handleDelete(item, type) {
        if (type == 'edit') {
          //编辑
          const { memoName, phone } = item;
          EditModal(true, {
            memoName,
            phone,
          });
        } else {
          let { lookNum, shotNum } = minNumber;
          // minNumber.shotNum = shotNum;
          //解除
          if (item.roleId == 8) {
            lookNum--;
            shotNum--;
          } else if (item.roleId == 81) {
            lookNum--;
          } else if (item.roleId == 82) {
            shotNum--;
          }
          createConfirm({
            iconType: 'warning',
            title: '提示',
            content: t('routes.devices.unbindWarning'),
            onOk: async () => {
              // tableRef.value.deleteTableDataRecord(item.id);
              deleteTableDataRecord(item.userName);
              minNumber.lookNum = lookNum;
              minNumber.shotNum = shotNum;
            },
          });
        }
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function openTargetModal() {
        console.log('openTargetModal');
        addopenModal(true);
      }
      async function saveTable() {
        // let tableData = tableRef.value.getDataSource() || [];
        // let fromData = await validate();
        let tableData = getDataSource();
        let SunNum = 0,
          permList = [];
        tableData?.map((ele) => {
          SunNum = SunNum + ele.muber;
          permList.push({
            staffPermTypeId: ele.id,
            num: ele.muber || 0,
            // takeLookNum:50,
          });
        });
        if (SunNum == 0) {
          return createMessage.warning('不支持两个权益都为空');
        }
        let res = await saveRights({
          companyId: modelRef.companyId,
          permList,
        });
        console.log('tableData', res);
        createMessage.success(t('common.optSuccess'));
        // reload();
        emit('update');
        closeModal();
      }
      function addTabledata(val) {
        console.log('addTabledata', val);
      }
      function getTableList(callback) {
        // let data = getFieldsValue();
        let tableList = unref(getDataSource());
        // setFieldsValue({
        //   subNum: Number(data.subNum) - 1,
        // });
        callback(tableList);
      }
      // function formatRoleName(val) {

      // },
      function handleAddUser(newUser) {
        let DataSource = getDataSource();
        let { shotNum, lookNum } = getFieldsValue();
        const total = DataSource?.length;
        let look = 0,
          shoot = 0;
        DataSource.map((ele) => {
          if (ele.roleId == 8) {
            look++;
            shoot++;
          } else if (ele.roleId == 81) {
            look++;
          } else if (ele.roleId == 82) {
            shoot++;
          }
        });
        console.log('look', look, shoot, 'shotNum, lookNum', shotNum, lookNum, newUser);
        // if ((newUser.roleId == 8 || newUser.roleId == 81) && !(look < lookNum)) {
        //   return createMessage.error('可带看员工数不足');
        // } else if ((newUser.roleId == 8 || newUser.roleId == 82) && !(shoot < shotNum)) {
        //   return createMessage.error('可拍摄员工数不足');
        // }
        minNumber.lookNum = lookNum;
        minNumber.shotNum = shotNum;
        insertTableDataRecord({
          nickName: newUser.memoName,
          userName: newUser.phone,
          phone: newUser.phone,
          roleName: '公司员工',
          roleId: newUser.roleId,
        });

        setFieldsValue({
          addeduser: total || 0,
        });
        createMessage.success(t('layout.setting.operatingTitle'));
      }
      return {
        register,
        handleDelete,
        numOnChange,
        numsOnChange,
        modelRef,
        schemas,
        registerForm,
        minNumber,
        handleVisibleChange,
        registerModal,
        openTargetModal,

        addopenModal,
        saveTable,
        closeModal,
        addTabledata,
        t,
        registerSubtable,
        reloadSubtable,
        handleAddUser,
        getTableList,
      };
    },
  });
</script>
