<template>
  <div>
    <BasicTable :rowSelection="{ type: 'checkbox' }" @register="registerTable" :clickToRowSelect="false" class="zjsqkList">
      <template #toolbar>
        <Authority>
          <a-button style="background-color: rgb(252, 139, 1); color: rgb(255, 255, 255);border: none;" type="primary"
            @click="handleCreate">提交申请</a-button>
        </Authority>
        <!-- <Authority>
          <Popconfirm title="您确定要批量删除数据" ok-text="确定" cancel-text="取消" @confirm="handleDeleteOrBatchDelete(null)">
            <a-button type="primary" color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority> -->
      </template>
      <!-- <template #status="{ record }">
        <Switch :checked="record.status === 1" :loading="record.pendingStatus" checkedChildren="启用" unCheckedChildren="禁用"
          @change="(checked: boolean) => statusChange(checked, record)" />
      </template> -->
      <template #action="{ record }">
        <TableAction :actions="[
          // {
          //   label: '浏览',
          //   icon: '' /**clarity:note-edit-line*/,
          //   // ifShow: record.servicealiasname,
          //   // ifShow: ((action) => action.servicealiasname),
          //   ifShow: record.servicealiasname,
          //   onClick: see.bind(null, record),
          // },
          // {
          //   label: '查看',
          //   icon: '' /**clarity:note-edit-line*/,
          //   onClick: handleEdit.bind(null, record),
          // },
          // {
          //   label: '编辑',
          //   icon: '' /**clarity:note-edit-line*/,
          //   color: 'warning',
          //   onClick: handleEdit.bind(null, record),
          // },
          // {
          //   label: '删除',
          //   icon: '' /**ant-design:delete-outlined'*/,
          //   color: 'error',
          //   ifShow: record.roleType != RoleEnum.SYS_ADMIN,
          //   popConfirm: {
          //     title: '是否确认删除',
          //     confirm: handleDelete.bind(null, record),
          //   },
          // },
          {
            label: '提交申请',
            icon: '' /**clarity:note-edit-line*/,
            // ifShow: record.servicealiasname,
            // ifShow: ((action) => action.servicealiasname),
            disabled: record.shzt != '未提交' && record.shzt != '审核不通过',
            // onClick: submitApply.bind(null, record),
            onClick: applyHandleEdit.bind(null, record),
          },
          {
            label: '移出',
            tooltip: '移出',
            // icon: 'ant-design:form-outlined',
            onClick: handleDelete.bind(null, record),
            disabled: record.shzt != '未提交' && record.shzt != '审核不通过'
          },
        ]" />
      </template>
      <template #pdate="{ record }">
        <Tag :color="'red'">
          {{
            record.publishdate ? moment(record.publishdate).format('YYYY-MM-DD HH:mm:ss') : ''
          }}
        </Tag>
      </template>
      <template #systemkey="{ record }">
        <span :id="'zjsqk' + record.id">{{ getAppName(record.systemkey, `zjsqk${record.id}`) }}</span>
      </template>
      <template #shr="{ record }">
        <span :id="'shr' + record.id">{{ getUser(record, `shr${record.id}`) }}</span>
      </template>
      <template #tjsqsj="{ record }">
        {{ record?.tjsqsj?.replace('.0', '') }}
      </template>
      <template #shyj="{ record }">
        <span :id="'shyj' + record.id">{{ getYJ(record, `shyj${record.id}`) }}</span>
      </template>
      <template #index="{ index }">
        {{ index + 1 }}
      </template>
      <template #status="{ record }">
        <Tag :style="`color:${record.shzt == '未提交' ? 'red' : '#05B069'};`">
          {{
            record.shzt
          }}
        </Tag>
      </template>
    </BasicTable>
    <MapSourceModal @register="registerModal" @success="handleSuccess" />
    <!-- 申请弹出框 -->
    <ApplyModal @register="registerModal" @success="applyHandleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, onBeforeMount, createVNode, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { delRole, setRoleStatus } from '/@/api/system/system';
import { useModal } from '/@/components/Modal';
import MapDrawer from './MapDrawer.vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import MapSourceModal from './MapSourceModal.vue';
import { columns, searchFormSchema } from './lib.data';
import { RoleEnum } from '/@/enums/roleEnum';
import { Authority } from '/@/components/Authority';
import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
import { useMessage } from '/@/hooks/web/useMessage';
import { Switch, Popconfirm, message, Modal } from 'ant-design-vue';
import { getAssemblyLibs } from '/@/api/dataAdmin/assembly';
//操作申请库资源
import Moment from 'moment'
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
import { deleteResInCar } from '/@/api/resource/plat';
import eventBus from '/@/utils/eventBus';
import ApplyModal from './applyModal/ApplyModal.vue';
import { list } from '/@/api/authorize/authorize';

export default defineComponent({
  name: 'RoleManagement',
  components: { BasicTable, MapDrawer, ApplyModal, MapSourceModal, TableAction, Authority, Switch, Popconfirm },
  setup() {

    const [registerModal, { openModal }] = useModal();
    const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRows, getSelectRowKeys }] = useTable({
      title: '组件资源列表',
      api: getAssemblyLibs,
      columns,
      formConfig: {
        labelWidth: 100,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: false,
      actionColumn: {
        width: 170,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      rowSelection: { type: 'checkbox' },
      rowKey: (record) => record.id,
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false
      },
    });
    const moment = Moment
    const { createMessage } = useMessage();
    const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(delRole, handleSuccess, setProps);
    selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
      // Demo:status为1的选择框禁用
      if (record.status === 1) {
        return { disabled: true };
      } else {
        return { disabled: false };
      }
    };
    nextTick(() => {
      setProps(selectionOptions);
    });

    function handleEdit(record: Recordable) {
      openModal(true, {
        record,
        isUpdate: true,
      });
    }

    function see(e) {
      console.log(e);
      if (e.servicealiasname) window.open(`../../mapview.html?onlineIde_${e.servicealiasname}`, '_blank');
    }

    //组件资源移出申请库
    const handleDelete = (record) => {
      console.log(record);
      Modal.confirm({
        title: '移出提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定移出该资源？',
        centered: true,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: (() => {
          deleteResInCar({
            idList: [record.applyCarInfo.id]
          }, { resInCarId: record.applyCarInfo.id }).then(() => applyHandleSuccess())
        })
      });
    }

    function handleSuccess() {
      openModal(false, {
        isUpdate: false,
      });
      reload();
    }

    /**
     * 申请成功
     */
    function applyHandleSuccess() {
      reload();
      eventBus.emit('assemblyCenter')
      eventBus.emit('getAssemblyLibsTotal')
    }

    const statusChange = async (checked, record) => {
      setProps({
        loading: true,
      });
      setSelectedRowKeys([]);
      resetSelectedRowKeys();
      const newStatus = checked ? 1 : 0;
      try {
        await setRoleStatus(record.id, newStatus);
        if (newStatus) {
          createMessage.success(`启用成功`);
        } else {
          createMessage.success('禁用成功');
        }
      } finally {
        setProps({
          loading: false,
        });
        reload();
      }
    };
    /**
     * 申请弹出框
     * @param record
     */
    function handleCreate() {
      var list = getSelectRowKeys();
      openModal(true, {
        isUpdate: false,
        sqzys: list
      });
    }
    /**
     * 申请弹出框
     * @param record
     */
    function applyHandleEdit(record: Recordable) {
      openModal(true, {
        record,
        isUpdate: true,
        sqzys: [record.resInfo.SERVICEID]
      });
    }

    eventBus.on("assemblyReload", () => reload())

    function submitApply(e) {
      console.log("submitApply:", e)
      queryFlowInfoPage({
        page: 1,
        rows: 1000000
      }).then(flowRes => {
        if (flowRes && flowRes.length) {
          var flow = flowRes.filter(i => i.FLOWNAME === '组件资源授权');
          if (flow.length) {
            let params = {
              bussInfo: {
                bussname: '组件资源授权',//业务名称
                flowid: flow[0].id,//流程id
                serverids: e.resInfo.SERVICEID//资源id
              }
            }
            submitExamine(params).then(res => {
              if (res.resp_code === 0 && res.resp_msg === '提交成功') {
                message.success('申请成功')
                reload();
              } else {
                message.error('申请失败')
              }
            })
          }

        }
      })
    }

    function getAppName(name, id) {
      list().then((r) => {
        if (r && r.length) {
          var app = r.find((i) => i.KEY == name);
          if (app) {
            var dom = document.getElementById(id);
            if (dom) {
              dom.innerHTML = app.NAME;
            }
          }
        }
      })
    }

    function getUser(item, id) {
      var shr = [];
      if (item?.shlc?.length > 1) {
        item.shlc.map((i, index) => {
          var lx = item?.shzt == '审核中' ? true : index != item.shlc.length - 1;
          if (index != 0 && lx) {
            shr.push(i.USER_NAME)
          }
        })
        var dom = document.getElementById(id);
        if (dom) {
          dom.innerHTML = shr.join(',')
        }
      }
    }

    function getYJ(item, id) {
      var shyj = [];
      if (item?.shlc?.length > 1) {
        item.shlc.map((i, index) => {
          var lx = item?.shzt == '审核中' ? true : index != item.shlc.length - 1;
          if (index != 0 && lx) {
            shyj.push(i.CHECKINFO)
          }
        })
        var dom = document.getElementById(id);
        if (dom) {
          dom.innerHTML = shyj.join(',')
        }
      }
    }

    return {
      getYJ,
      getUser,
      getAppName,
      applyHandleEdit,
      applyHandleSuccess,
      submitApply,
      moment,
      createMessage,
      registerTable,
      // registerDrawer,
      registerModal,
      handleCreate,
      see,
      handleEdit,
      handleDelete,
      handleSuccess,
      RoleEnum,
      hasBatchDelete,
      handleDeleteOrBatchDelete,
      statusChange,
    };
  },
});
</script>
<style>
.zjsqkList .ant-table-fixed-header .ant-table-scroll .ant-table-header{
    width: 1404px !important;
}
</style>