<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="(caseId||fusionId)?'设置权限':'设置场景权限'"
    @cancel="resetFields"
    @ok="handleSubmit"
    :width="1100"
    :min-height="0"
  >
    <div class="pt-2px pr-3px">
      <div style="margin-left: 17px">提示：若添加的用户已有部分{{fusionId?'':'场景'}}权限，新的权限覆盖原有的权限。</div>
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <BasicTable class="powesrTable" ref="tableRef" @register="registerTables">
        <template #toolbar>
          <a-button type="primary" v-if="getCheckPerm('scenes-powers-add')" @click="addPowes">
            新增
          </a-button>
        </template>
        <template #sceneName="{ record }">
          <a v-if="caseId" @click="handleRyno(record)"> {{ record.ryNo }} </a>
          <span v-else>{{ record.ryNo }}</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '编辑',
                ifShow: getCheckPerm('scenes-powers-edit'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                disabled: record.canDel != 0,
                color: 'error',
                ifShow: getCheckPerm('scenes-powers-delete'),
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
      <detailModal @register="registerDetail" @update="reload" />
      <ryNoSceneModal @register="registerryNoModal" @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 ryNoSceneModal from './ryNoSceneModal.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, ryNoSceneModal, BasicForm, BasicTable, TableAction, detailModal },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const tableRef = ref(null);

      const numRef = ref(null);
      const caseId = ref(null);
      const fusionId = ref(null);
      const sourceType = ref(null);
      const type = ref(0);
      const fileFlow = reactive({
        showList: true,
      });
      const [registerryNoModal, { openModal: openryNoModal }] = useModal();
      const [registerDetail, { openModal: openDetaileModal }] = useModal();
      const columnssss: BasicColumn[] = [
        {
          title: '警员ID',
          dataIndex: 'ryNo',
          slots: { customRender: 'sceneName' },
          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 }) => {
            if (type.value == 1 && record.canEditLook == 1) return '编辑';
            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 [registerTables, { reload, getColumns }] = useTable({
        api: getAuthList,
        title: `已授权列表`,
        columns: columnssss,
        useSearchForm: false,
        immediate: false,
        searchInfo: {
          num: numRef,
          sourceType: sourceType,
          caseId: caseId,
          authType: type,
          fusionId: fusionId,
        },
        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) => {
              type.value = value.target.value;
              fileFlow.showList = value.target.value ? false : true;
              reload();
            },
          },
          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) {
        console.log('onDataReceive', data);
        modelRef.value = data;
        numRef.value = data.sourceType=='fusion'?data.fusionId: data.num;
        sourceType.value = data.sourceType;
        fusionId.value = data.fusionId;
        caseId.value = data.caseId;
        resetFields();
        const { authType } = await getAuthType({ num: numRef.value,  sourceType: sourceType.value });
        fileFlow.showList = authType ? false : true;
        type.value = authType;
        setFieldsValue({
          type: data.sceneName,
          authType,
        });
        let disabled = !(
          userName.value == data.userName ||
          roleId.value == 1 ||
          roleId.value == 45 ||
          roleId.value == 48
        );

        updateSchema({
          field: 'authType',
          componentProps: {
            disabled: data.tableType == 1,
            options: [
              { label: '授权浏览', value: 0, disabled: disabled && authType == 1 },
              { label: '公开浏览', value: 1, disabled: disabled && authType == 0 },
            ],
          },
        });
        reload();
        // setTimeout(async () => {
        // }, 500);
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('res', params);
          const res = await setAuthType({
            num: numRef.value,
            caseId: caseId.value,
            ...params,
            lookAuth: params.authType,
            sourceType: sourceType.value,
          });
          console.log('res', res);
          closeModal();
          resetFields();
          // createMessage.success('权限设置成功');
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function addPowes() {
        console.log('addPowes', getColumns(), columnssss);
        openDetaileModal(true, { num: numRef.value, caseId: caseId.value, qxType: fileFlow.showList, sourceType: sourceType.value });
      }
      function handleRyno(record) {
        openryNoModal(true, {...record, caseId: caseId.value, sourceType: sourceType.value});
      }
      function handleEdit(record: Recordable) {
        openDetaileModal(true, record);
      }
      async function handleDelete(record: Recordable) {
        createConfirm({
          title: '删除',
          content: `确定要删除 ${record.ryNickName} 吗？`,
          onOk: async () => {
            await delAuth({ id: record.id, num: numRef.value, sourceType: sourceType.value, });
            createMessage.success('删除成功');
            reload();
          },
        });
      }
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        handleRyno,
        fileFlow,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
        getCheckPerm,
        handleEdit,
        handleDelete,
        registerTables,
        registerDetail,
        registerryNoModal,
        openDetaileModal,
        addPowes,
        reload,
        userName,
        caseId,
        fusionId,
        tableRef,
      };
    },
  });
</script>

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