<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="设置场景权限"
    @cancel="resetFields"
    @ok="handleSubmit"
    :width="1000"
    :min-height="0"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <BasicTable v-show="fileFlow.showList" class="powesrTable" @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="addPowes"> 新增 </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '编辑',
                ifShow: getCheckPerm('scenes-move'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                color: 'error',
                ifShow: getCheckPerm('scenes-delete'),
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
      <detailModal @register="registerDetail" @update="reload" />
    </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 { sceneMove } from '/@/api/operate';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import detailModal from './detailModal.vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { getAuthList, addAuth, delAuth } from '/@/api/operate';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, BasicTable, TableAction, detailModal },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const numRef = ref(null);
      const fileFlow = reactive({
        showList: true,
      });
      const [registerDetail, { openModal: openDetaileModal }] = useModal();
      const columns: BasicColumn[] = [
        {
          title: '警员ID',
          dataIndex: 'ryId',
          width: 150,
        },
        {
          title: '姓名',
          dataIndex: 'ryNickName',
          width: 180,
        },
        {
          title: '浏览权限',
          dataIndex: 'lookAuth',
          customRender: ({ record }) => {
            return record.lookAuth == 1 ? '不限时间' : record.lookAuth == 0 ? '无权' : `${record.lookEndTime} 截止`;
          },
          width: 180,
        },
        {
          title: '编辑权限',
          dataIndex: 'editAuth',
          customRender: ({ record }) => {
            return record.editAuth == 1 ? '不限时间' : record.editAuth == 0 ? '无权' : `${record.editEndTime} 截止`;
          },
          width: 180,
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 120,
        },
      ];
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const { createMessage, createConfirm } = useMessage();
      const [registerTable, { reload, getRawDataSource }] = useTable({
        api: getAuthList,
        title: `已授权列表`,
        columns: columns,
        useSearchForm: false,
        immediate: false,
        searchInfo: {
          num: numRef,
        },
        afterFetch: (T) => {
          let { authType } = getRawDataSource();
          setFieldsValue({
            authType,
          });
          fileFlow.showList = authType ? false : true;
          return T;
        },
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        canResize: true,
        rowKey: 'id',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'pageInfo.list',
          totalField: 'total',
        },
      });
      const schemas: FormSchema[] = [
        {
          field: 'authType',
          component: 'RadioGroup',
          defaultValue: 0,
          componentProps: {
            options: [
              { label: '授权用户', value: 0 },
              { label: '公开浏览', value: 1 },
            ],
            onChange: (value) => {
              fileFlow.showList = value.target.value ? false : true;
              console.log('fileFlow.showList', value.target.value, fileFlow.showList);
            },
          },
          label: '授权方式',
          colProps: {
            span: 24,
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
        labelWidth: 80,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        modelRef.value = data;
        numRef.value = data.num;
        console.log('num', numRef.value);
        reload();
        resetFields();
        setFieldsValue({
          type: data.sceneName,

        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('res', params);
          const res = await addAuth({num:numRef.value,...params});
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success('场景迁移成功。');
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function addPowes() {
        openDetaileModal(true, { num: modelRef.value.num});
      }
      function handleEdit(record: Recordable) {
        openDetaileModal(true, record);
      }
      async function handleDelete(record: Recordable) {
        createConfirm({
          title: '删除',
          content: `确定要删除 ${record.ryNickName} 吗？`,
          onOk: async () => {
            await delAuth({ id: record.id })
            createMessage.success('删除成功');
            reload();
          },
        });
      }
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
        getCheckPerm,
        handleEdit,
        handleDelete,
        registerTable,
        registerDetail,
        openDetaileModal,
        addPowes,
        reload,
      };
    },
  });
</script>

<style lang="less" scoped>
  .powesrTable {
  }
</style>
