<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="设置场景权限"
    @cancel="resetFields"
    @ok="handleSubmit"
    :width="1000"
    :min-height="0"
  >
    <div class="pt-2px pr-3px">{{roleId}}
      <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" v-if="getCheckPerm('scenes-powers-add')" @click="addPowes"> 新增 </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '编辑',
                ifShow: getCheckPerm('scenes-powers-edit'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                color: 'error',
                ifShow: getCheckPerm('scenes-powers-delete'),
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
      <detailModal @register="registerDetail" @update="reload" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, 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, getAuthType, setAuthType, delAuth } from '/@/api/operate';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import { useUserStore } from '/@/store/modules/user';
  import dayjs from 'dayjs';
  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 ? '无权' : `${dayjs(record.lookEndTime).format('YYYY-MM-DD HH:mm')} 截止`;
          },
          width: 150,
        },
        {
          title: '编辑权限',
          dataIndex: 'editAuth',
          customRender: ({ record }) => {
            return record.editAuth == 1 ? '不限时间' : record.editAuth == 0 ? '无权' : `${dayjs(record.editEndTime).format('YYYY-MM-DD HH:mm')} 截止`;
          },
          width: 150,
        },
        {
          title: '可授权他人',
          dataIndex: 'canLook',
          customRender: ({ record }) => {
            return record.canEditLook == 1 ? '编辑和查看' : record.canAuthLook == 1 ? '查看' : `无权`;
          },
          width: 120,
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 80,
        },
      ];
      const permissionStore = usePermissionStore();
      const userStore = useUserStore();
      const userName = computed(() => userStore.getUserInfo?.userName);
      const roleId = computed(() => userStore.getUserInfo?.roleId);
      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: '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, updateSchema }] = useForm({
        labelWidth: 80,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      async function onDataReceive(data) {
        modelRef.value = data;
        numRef.value = data.num;
        reload();
        resetFields();
        const { authType } = await getAuthType({num:numRef.value});;
        fileFlow.showList = authType ? false : true;
        setFieldsValue({
          type: data.sceneName,
          authType,
        });
        console.log('roleId', roleId.value, (userName.value != data.userName || roleId.value != 1 || roleId.value != 45));
        updateSchema({
          field: 'authType',
          componentProps: {
            disabled: !(userName.value == data.userName || roleId.value == 1 || roleId.value == 45),
          },
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('res', params);
          const res = await setAuthType({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,
        userName,
      };
    },
  });
</script>

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