
<template>


<ResizePageWrapper   :hasLeft="false">
 
 
 <template #resizeRight>
<BasicTable @register="registerTable" isMenuTable ref="tableRef"  :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"
   
  >
       
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <CustomButtonModal v-else-if="button.buttonType == 'modal'" :info="button" />
            <a-button v-else :type="button.buttonType === 'danger' ? 'default' : button.buttonType || 'primary'" :danger="button.buttonType === 'danger'" >
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          
          
         
          <template v-if="column.dataIndex === 'action'">
          
           <TableAction
              :actions="getLessActions(record)"
              :dropDownActions="getMoreActions(record)"
            />
          </template>
          
          <template v-else-if="column.dataIndex && column?.listStyle">
            <span :style="executeListStyle(getValue(record, column, 'style'), column?.listStyle)">{{
              getValue(record, column, 'value')
            }}</span>
          </template>
        </template>
        
           
        
      </BasicTable>
 </template>
 
  
  
   <ScrwModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   
  
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref, createVNode, 
} from 'vue';
  
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getMesProductionTaskPage, deleteMesProductionTask} from '/@/api/scgl/scrw';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
    import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  import { executeListStyle, getValue } from '/@/hooks/web/useListStyle';//列表样式配置
  import { useRouter } from 'vue-router';
  
  
  
  
  
  import { useModal } from '/@/components/Modal';
  
  
  
  import ScrwModal from './components/ScrwModal.vue';
  
  
  
  
  
  
  
  import { searchFormSchema, columns  } from './components/config';
  
  import Icon from '/@/components/Icon/index';
   
   
  
  
  
  
  
  

  
   const listSpliceNum = ref(3); //操作列最先展示几个
   
  
  


 
  import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';
  import {recallMesProductionPlan, revokeMesProductionTask} from "/@/api/scgl/scjh";
  import {useUserStore} from "/@/store/modules/user";

  const pageParamsInfo = ref<any>({});
  const { enableLockeData,handleOpenFormEnableLockeData, handleCloseFormEnableLocke, handleHasEnableLocke } =
    useConcurrentLock();

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth, hasPermission } = usePermission();

  const filterColumns = filterColumnAuth(columns);
  const tableRef = ref();
  

  
  

  
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(["view","edit","ddzh","delete","chehui"]);
  const buttonConfigs = computed(()=>{
    const list = [{"buttonId":"2008813468518432768","name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true,"isUse":true},{"buttonId":"2008813468518432769","name":"新增","code":"add","icon":"ant-design:plus-outlined","isDefault":true,"isUse":true},{"buttonId":"2008813468518432770","name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isUse":true,"isEnableLock":true},{"isUse":true,"name":"撤回","code":"chehui","icon":"ant-design:loading-3-quarters-outlined","isDefault":false,"setting":[],"showType":"top","buttonType":"primary"},{"buttonId":"2008813468518432771","name":"打印","code":"sclld","icon":"ant-design:file-text-outlined","isDefault":false,"isUse":true,"setting":[],"showType":"top","buttonType":"primary"},{"isUse":true,"name":"订单转换","code":"ddzh","icon":"","isDefault":false,"setting":[],"showType":"inline","buttonType":"modal","modal":{"bindModal":"2010615112372113410","innerParams":[{"name":"任务ID","type":"value","value":"1","apiConfig":{"path":"CodeGeneration/selection","method":"GET","apiId":"93d735dcb7364a0f8102188ec4d77ac7"},"component":"{\"table\":\"table_19041\",\"field\":\"ren_wuid1465\"}"},{"name":"任务编号","type":"value","value":"CCRW001","apiConfig":{"path":"CodeGeneration/selection","method":"GET","apiId":"93d735dcb7364a0f8102188ec4d77ac7"},"component":"{\"table\":\"table_19041\",\"field\":\"zhuan_huan_qian_ding_dan5032\"}"}],"outParams":[{"name":"转换后","component":"{\"table\":\"table_19041\",\"field\":\"zhuan_huan_hou_ding_dan6513\"}","mainComponent":""}],"modalWidth":900,"modalWidthUnit":"px","modalHeight":300,"modalHeightUnit":"px","title":"订单转换","confirm":"","cancel":"","open":"","close":""}},{"buttonId":"2008813468518432772","name":"删除","code":"delete","icon":"ant-design:delete-outlined","isDefault":true,"isUse":true}]
    return filterButtonAuth(list);
  })

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = {view : handleView,add : handleAdd,edit : handleEdit,delete : handleDelete,chehui:handleBack}

  
  const { currentRoute } = useRouter();
  
  
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);
  
   
   
  
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);
  
   
  
  const [registerModal, { openModal }] = useModal();
  
  
   
   
  const [registerTable, { reload,   }] = useTable({
    title: 'Scrw列表',
    api: getMesProductionTaskPage,
    rowKey: 'id',
    columns: filterColumns,
    pagination: {
      pageSize: 10,
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [],
      showResetButton: false,
    },
     bordered:false,
          beforeFetch: (params) => {
      pageParamsInfo.value = {...params, FormId: formIdComputedRef.value,PK: 'id' }
      return pageParamsInfo.value;
    },
    afterFetch: (res) => {
      
      
       
      
      selectedKeys.value = [];
      selectedRowsData.value = [];
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    
    
    striped: false,
    actionColumn: {
      width: 225,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery:  false,
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });

  
  

  function buttonClick(code) {
    
    btnEvent[code]();
  }
    
  
  function handleAdd() {
  
 
      openModal(true, { isUpdate: false, });
 
      }
      
  
  async function handleEdit(record: Recordable) {
    const hasNonDraft = (record.zt !== '草稿' && record.zt !== '未开始');
    if (hasNonDraft) {
      Modal.warning({
        title: '提示',
        content: '开工之后无法编辑',
      });
      return;
    }
    let field = 'id';
  try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'edit');
      if (hasIn) { 
        let res = await handleOpenFormEnableLockeData(
          record[field],
          formIdComputedRef.value,
        );
        if (res !== null) {
          return;
        }
      } 
    
    let info = {
      id: record[field],
      
      isUpdate: true,
      
    };
    
    openModal(true, info);
      } catch (error) {} 
  }
  
   
  
    
  function handleDelete(record: Recordable) {
  deleteList([record.id],record);
  }

  function handleBack(record: Recordable) {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否撤回？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        let zt = record.zt;
        if (zt != '未开始') {
          Modal.warning({
            title: '提示',
            content: '不是未开始的任务无法撤回',
          });
          return;
        }
        const id = record.id;
        revokeMesProductionTask(id).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: '撤回成功！',
          });
        });
      },
      onCancel() {},
    });
  }
  const userStore = useUserStore();
    
  function deleteList(ids,record) {
    //当前登录人的id
    let userId = userStore.getUserInfo.id;
    //创建人的id
    let createUserId = record.createUserId;
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        if (userId==createUserId) {
          if (record.zt=='草稿') {
            deleteMesProductionTask(ids).then((_) => {
              handleSuccess();
              notification.success({
                message: 'Tip',
                description: t('删除成功！'),
              });
            });
          } else {
            notification.warning({
              message: 'Tip',
              description: t('已进行的任务不能删除！'),
            });
          }
        } else {
          notification.warning({
            message: 'Tip',
            description: t('不是本人的任务不能删除！'),
          });
        }
      },
      onCancel() {},
    });
  }
  
  
  
  
  
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  
  function customRow(record: Recordable) {
    return {
      
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
      },
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("scrw:edit")) {
          handleEdit(record);
        }
      },
    };
  }
  
  function handleSuccess() {
    
    
        selectedKeys.value = [];
        selectedRowsData.value = [];
    reload();
    
  }
    
  
    function handleFormSuccess() {
    handleSuccess();
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }
  function handleFormCancel() {
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }

  
  function handleView(record: Recordable) {
  let info={
      isView: true,
     id: record.id,
    }

    openModal(true, info);    
  }
  
  
  
  
  function getLessActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(0, listSpliceNum.value);
  }
  function getMoreActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(listSpliceNum.value);
  }
  function getActions(record: Recordable):ActionItem[] {
    record.isCanEdit = false;
    
    let actionsList: ActionItem[] = [];  
    actionButtonConfig.value?.map((button) => {
    if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        actionsList.push({
          ...button,
           
          auth: `scrw:${button.code}`,
          label: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code]?.bind(null, record),
        });
      } else {
        if (!['edit', 'delete'].includes(button.code)) {
          actionsList.push({
             
            auth: `scrw:${button.code}`,
            label: button?.name,
            onClick: btnEvent[button.code]?.bind(null, record),
          });
        } 
      }
    });
    return actionsList;
  }
  
  
</script>
<style lang="less" scoped>

  :deep(.ant-table-selection-col) {
    width: 50px;
  }

  .show{
    display: flex;
  }

  .hide{
    display: none !important;
  }
  
  
  
  
</style>
