<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="fileFlow.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 class="powesrTable" @register="registerTable">
        <!-- <template #toolbar>
          <a-button type="primary" v-if="getCheckPerm('scenes-powers-add')" @click="addPowes">
            新增
          </a-button> 
        </template>-->
        <template #sceneName="{ record }">
          <a @click="handleRyno(record)"> {{ record.ryNo }} </a>
        </template>
        <template #href="{ record }">
          <a
            v-if="record.webSite"
            target="_blank"
            :title="record.title"
            :href="record.webSite"
            >{{ record.title }}</a
          >
          <span v-else-if="record.title">{{ record.title }}</span>
          <span v-else>-</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" />
    </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 { getCaseNumByRyId } from '/@/api/media';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import detailModal from './detailModal.vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { operateSceneList, 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 ryNo = ref(null);
      const caseId = ref(null);
      const numRef = ref(null);
      const type = ref(0);
      const fileFlow = reactive({
        title: '场景权限',
        showList: true,
      });
      const [registerDetail, { openModal: openDetaileModal }] = useModal();
      const columns: BasicColumn[] = [
        {
          title: '场景标题',
          dataIndex: 'sceneName',
          ellipsis: true,
          slots: { customRender: 'href' },
          resizable: true,
          minWidth: 150,
          width: 150,
        },
        {
          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,
        },
      ];
      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: getCaseNumByRyId,
        title: `已授权列表`,
        columns: columns,
        useSearchForm: false,
        immediate: false,
        searchInfo: { ryId: ryNo, caseId: caseId },
        // 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) => {
              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) {
        modelRef.value = data;
        ryNo.value = data.ryId;
        caseId.value = data.caseId;
        fileFlow.title = data.ryNickName + '拥有的场景权限';
        numRef.value = data.num;
        console.log('data', caseId.value);
        reload();
        const { authType } = await getAuthType({ num: numRef.value, caseId: caseId.value });
        fileFlow.showList = authType ? false : true;
        type.value = authType;
        setFieldsValue({
          type: data.sceneName,
          authType,
        });
        console.log(
          'roleId',
          roleId.value,
          userName.value != data.userName || roleId.value != 1 || roleId.value != 45 || roleId.value != 48,
        );
        let disabled = !(
          userName.value == data.userName ||
          roleId.value == 1 ||
          roleId.value == 45 ||
          roleId.value == 48
        );
        updateSchema({
          field: 'authType',
          componentProps: {
            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,
            ...params,
            lookAuth: params.authType,
          });
          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, caseId: caseId.value, qxType: fileFlow.showList });
      }
      function handleRyno(record) {
        // register({ isShow, data });
      }
      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,
        handleRyno,
        fileFlow,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
        getCheckPerm,
        handleEdit,
        handleDelete,
        registerTable,
        registerDetail,
        openDetaileModal,
        addPowes,
        reload,
        userName,
      };
    },
  });
</script>

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