<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.devices.title')"
    @ok="saveTable"
    width="700px"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #userName="{ model, field }">
          {{ model[field] }}
        </template>
        <template #name="{ model, field }">
          {{ model[field] }}
        </template>
        <template #addeduser="{ model, field }">
          {{ model[field] || 0 }}
          <a-button
            :disabled="model[field] >= modelRef.subNum"
            @click="openTargetModal()"
            type="primary"
            preIcon="ic:outline-person-add"
          >
            {{ t('routes.devices.add') }}{{ t('routes.devices.title') }}
          </a-button>
        </template>
        <template #subNum="{ model, field }">
          <!-- {{ model[field] }}  
            
            @press-enter="deviceMapping"-->
          <input-number
            v-model:value="model[field]"
            style="width: 260px; text-align: center"
            class="justify-center suNum"
            :min="0"
            @blur="
              () => {
                numOnChange(true, field);
              }
            "
            :max="999"
          >
            <template #addonBefore>
              <a-button
                size="small"
                type="link"
                :disabled="model[field] == 0"
                @click="
                  () => {
                    numsOnChange(false, field);
                  }
                "
              >
                <Icon icon="ic:baseline-minus" :size="20" />
              </a-button>
            </template>
            <template #addonAfter>
              <a-button
                size="small"
                :disabled="model[field] == 999"
                type="link"
                @click="
                  () => {
                    numsOnChange(true, field);
                  }
                "
              >
                <Icon icon="ic:round-plus" :size="20" />
              </a-button>
            </template>
          </input-number>
        </template>
      </BasicForm>
      <div class="table_list">
        <BasicTable
          @register="registerSubtable"
          :beforeEditSubmit="beforeEditSubmit"
          :searchInfo="searchInfo"
        >
          <template #action="{ record }">
            <TableAction
              :actions="[
                // {
                //   label: '编辑',
                //   icon: 'mdi:account-edit-outline',
                //   onClick: handleDelete.bind(null, record, 'edit'),
                // },
                {
                  icon: 'mdi:account-multiple-remove-outline',
                  label: '删除',
                  onClick: handleDelete.bind(null, record, 'unbond'),
                },
              ]"
            />
          </template>
        </BasicTable>
        <AddModal @tablelist="getTableList" @register="registerModal" @submit="handleAddUser" />
      </div>
    </div>
    <EditModal @register="registerEdit" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn, TableAction } from '/@/components/Table';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { selectUserList, saveSubUsers } from '/@/api/corporation/modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import EditModal from './EditModal.vue';
  import { Icon } from '/@/components/Icon/index';
  // import { tableState } from './types/hooks';
  import { InputNumber } from 'ant-design-vue';
  import AddModal from './AddModal.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      BasicTable,
      AddModal,
      TableAction,
      EditModal,
      InputNumber,
      Icon,
    },
    props: {
      userData: { type: Object },
    },
    emits: ['addtable', 'register', 'update'],
    setup(props, { emit }) {
      const { t } = useI18n();
      const { createConfirm, createMessage } = useMessage();

      const [registerModal, { openModal: addopenModal }] = useModal();

      const modelRef = reactive({
        id: 0,
        subNum: 0,
      });
      const searchInfo = reactive({
        limit: 9999,
        id: 0,
        page: 1,
      });
      const columns: BasicColumn[] = [
        {
          title: t('common.fullName'),
          dataIndex: 'nickName',
          edit: true,
          editRule: async (text) => {
            if (text && text.length > 25) {
              return t('routes.corporation.maxlength');
            }
            return '';
          },
          width: 160,
        },
        {
          title: t('common.mobile'),
          edit: true,
          editRule: true,
          width: 160,
          dataIndex: 'userName',
        },
        {
          title: '角色',
          width: 100,
          dataIndex: 'roleName',
        },
        {
          title: 'roleId',
          width: 150,
          ifShow: false,
          dataIndex: 'roleId',
        },
        {
          title: t('common.operating'),
          dataIndex: '',
          slots: { customRender: 'action' },
          width: 80,
        },
      ];
      const schemas: FormSchema[] = [
        {
          field: 'userName',
          component: 'Input',
          label: `${t('routes.corporation.enterpriseId')} ：`,
          slot: 'userName',
          labelWidth: 200,
        },
        {
          field: 'name',
          label: `${t('routes.corporation.enterpriseName')} ：`,
          slot: 'name',
          component: 'Input',
          labelWidth: 200,
        },
        {
          field: 'shotNum',
          component: 'InputNumber',
          slot: 'subNum',
          label: `可拍摄员工数 ：`,
          labelWidth: 200,
          rules: [
            {
              required: false,
              // @ts-ignore
              validator: async (rule, value) => {
                let { addeduser, lookNum } = getFieldsValue();
                if (value < addeduser - lookNum) {
                  return Promise.reject('可添加员工总数应大于已添加员工数');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: () => {
            return {
              // xxxx props schema, tableAction, formModel  checkDevice
              min: 0,
              max: 999,
              onChange: numOnChange,
            };
          },
        },
        {
          field: 'lookNum',
          component: 'InputNumber',
          slot: 'subNum',
          label: `可带看员工数 ：`,
          labelWidth: 200,
          rules: [
            {
              required: false,
              // @ts-ignore
              validator: async (rule, value) => {
                let { addeduser, shotNum } = getFieldsValue();
                console.log('validator', value, addeduser);
                if (value < addeduser - shotNum) {
                  return Promise.reject('可添加员工总数应大于已添加员工数');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: () => {
            return {
              // xxxx props schema, tableAction, formModel  checkDevice
              max: 999,
              min: 0,
              onChange: numsOnChange,
            };
          },
        },
        {
          field: 'addeduser',
          label: `${t('routes.devices.addeduser')}`,
          labelWidth: 200,
          slot: 'addeduser',
          component: 'Input',
        },
      ];
      const [
        registerForm,
        { setFieldsValue, resetFields, getFieldsValue, validate, validateFields },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [
        registerSubtable,
        {
          reload: reloadSubtable,
          updateTableDataRecord,
          deleteTableDataRecord,
          getDataSource,
          insertTableDataRecord,
        },
      ] = useTable({
        title: `${t('routes.devices.listTile')}`,
        rowKey: 'phone',
        api: selectUserList,
        immediate: false,
        columns: columns,
        showIndexColumn: false,
        bordered: true,
        pagination: false,
      });

      const [registerEdit, { openModal: EditModal }] = useModal();
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      async function onDataReceive(data) {
        console.log('Data Received', data.record);
        // 方式1;
        const { id, lookNum = 0, shotNum = 0 } = data.record;
        resetFields();
        setFieldsValue({
          ...data.record,
        });
        modelRef.id = id;
        modelRef.subNum = lookNum + shotNum;

        searchInfo.id = id;
        await reloadSubtable();

        const total = getDataSource();
        console.log('total', total);
        setFieldsValue({
          addeduser: total?.length || 0,
        });
      }
      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) {
        console.log('handleDelete', item, type);
        if (type == 'edit') {
          //编辑
          const { memoName, phone } = item;
          EditModal(true, {
            memoName,
            phone,
          });
        } else {
          //解除
          createConfirm({
            iconType: 'warning',
            title: '提示',
            content: t('routes.devices.unbindWarning'),
            onOk: async () => {
              // tableRef.value.deleteTableDataRecord(item.id);
              deleteTableDataRecord(item.userName);
            },
          });
        }
      }

      async function beforeEditSubmit({ record, _, key, value }) {
        updateTableDataRecord(record.userName, { ...record, [key]: value });
      }
      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 res = await saveSubUsers({
          id: modelRef.id,
          shotNum: fromData.shotNum,
          lookNum: fromData.lookNum,
          subUsers: tableData,
        });
        console.log('saveTable', res, fromData);
        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);
        if (!(look < lookNum)) {
          return createMessage.error('可带看员工数不足');
        } else if (!(shoot < shotNum)) {
          return createMessage.error('可拍摄员工数不足');
        }
        let obj = {
          8: '带看&拍摄员工',
          81: '带看员工',
          82: '拍摄员工',
        };
        insertTableDataRecord({
          nickName: newUser.memoName,
          userName: newUser.phone,
          phone: newUser.phone,
          roleName: obj[newUser.roleId],
          roleId: newUser.roleId,
        });
        setFieldsValue({
          addeduser: total || 0,
        });
        createMessage.success(t('layout.setting.operatingTitle'));
      }
      return {
        register,
        handleDelete,
        registerEdit,
        numOnChange,
        numsOnChange,
        modelRef,
        schemas,
        columns,
        registerForm,

        handleVisibleChange,
        beforeEditSubmit,
        registerModal,
        openTargetModal,

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