<template>
  <el-form :model="state.queryParams" ref="queryParamsRef" :inline="true" @submit.native.prevent>
    <el-form-item label="关键词" prop="Keyword">
      <el-input v-model="state.queryParams.Keyword" placeholder="工单标题/工单编码" clearable @keyup.enter="handleQuery" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery" :loading="state.loading">
        <SvgIcon name="ele-Search" class="mr5" />查询
      </el-button>
      <el-button @click="resetQuery(queryParamsRef)" :loading="state.loading" class="default-button">
        <SvgIcon name="ele-Refresh" class="mr5" />重置
      </el-button>
    </el-form-item>
  </el-form>
  <el-table
      :data="state.tableData"
      v-loading="state.loading"
      row-key="id"
      @selection-change="handleSelectionChange"
      max-height="300"
      ref="multipleTableRef"
  >
    <el-table-column type="selection" label="重复件" width="80" :reserve-selection="true" v-if="props.formData.isRepeat === 'true'" />
    <el-table-column prop="phoneNo" label="工单标题" show-overflow-tooltip width="180">
      <template #default="{ row }">
        {{ row.title }}
      </template>
    </el-table-column>
    <el-table-column prop="hotspotName" label="热点分类" show-overflow-tooltip> </el-table-column>
    <el-table-column prop="no" label="工单编码" show-overflow-tooltip> </el-table-column>
    <el-table-column prop="currentStepName" label="当前环节" show-overflow-tooltip></el-table-column>
    <el-table-column prop="statusText" label="状态" width="70" fixed="right" align="center"></el-table-column>
    <el-table-column prop="statusText" label="操作" width="170" fixed="right" align="center">
      <template #default="{ row }">
        <el-button @click="onSupply(row)" link type="primary" v-auth="'business:order:supply'"> 补充 </el-button>
        <el-button @click="onRevoke(row)" link type="primary" v-auth="'business:order:revoke'"> 撤销 </el-button>
        <el-button @click="onSupervise(row)" link type="primary"> 督办 </el-button>
      </template>
    </el-table-column>
  </el-table>
  <pagination
      :total="state.total"
      v-model:page="state.queryParams.PageIndex"
      v-model:limit="state.queryParams.PageSize"
      @pagination="searchHistory"
  />
  <!-- 补充信息 -->
  <order-supply ref="SupplyRef" @onSupplySuccess="onSupplySuccess" />
  <!-- 工单撤销 -->
  <order-revoke ref="orderRevokeRef" @onRevokeSuccess="onRevokeSuccess" />
  <!-- 工单督办 -->
  <order-super-vise ref="orderSuperviseRef" @onSuperviseSuccess="onSuperviseSuccess" />
</template>
<script setup lang="ts" name="orderAcceptHistory">
import {reactive, ref, defineAsyncComponent, onMounted, watch} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import {throttle} from "/@/utils/tools";
import {auth} from "/@/utils/authFunction";
import {historyOrder} from "/@/api/business/order";
import {useRoute} from "vue-router";

const OrderSuperVise = defineAsyncComponent(() => import('/@/views/business/supervise/components/Order-supervise.vue')); // 工单督办
const OrderSupply = defineAsyncComponent(() => import('/@/views/business/order/components/Order-supply.vue')); // 补充信息
const OrderRevoke = defineAsyncComponent(() => import('/@/views/business/order/components/Order-revoke.vue')); // 工单撤销
const props = defineProps({
  orderId: {
    type: String,
    default: '',
  },
  formData:{ // 表单填写的数据
    type: Object,
    default: () => {
      return {};
    },
  }
});
const emit = defineEmits(['handleSelectionChange']);
const state = reactive<any>({
  tableData: [], // 历史工单
  total: 0, // 历史工单总条数
  queryParams: {
    PageIndex: 1, // 当前页
    PageSize: 10, // 每页条数
    Keyword: '', // 关键字
  },
  loading:false,
})
const queryParamsRef = ref<RefType>(); // 历史工单查询参数
const multipleSelection = ref<any[]>([]); // 重复件表格选中项
const multipleTableRef = ref<RefType>(); // 重复件表格ref
/** 搜索按钮操作 */
const handleQuery = throttle(() => {
  state.queryParams.PageIndex = 1;
  searchHistory();
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  handleQuery();
}, 300);
watch(()=>props.formData,(val)=>{
  if(val.id){
    searchHistory(props.formData);
  }
})
/** 获取历史工单 */
const searchHistory = throttle(async (orderDetail?: any) => {
  if (!auth('business:order:history')) ElMessage.error('抱歉，您没有权限查询历史工单！');
  else {
    state.loading = true;
    let request = {
      ...state.queryParams,
      PhoneNo: props.formData.contact,
      OrderId: props.orderId, //传入id 排除重复工单选择自己
    };
    try {
      const response = await historyOrder(request);
      state.tableData = response?.result.items ?? [];
      state.total = response?.result.total;
      state.loading = false;
      if (orderDetail) {
        if (orderDetail.duplicateIds && orderDetail.duplicateIds.length) {
          multipleSelection.value = orderDetail.duplicateIds;
          for (let i of multipleSelection.value) {
            for (let j of state.tableData) {
              if (i === j.id) {
                setTimeout(() => {
                  multipleTableRef.value!.toggleRowSelection(j, true);
                }, 0);
              }
            }
          }
        }
      }
    } catch (error) {
      state.loading = false;
    }
  }
}, 300);
// 右边表格选中重复件
const handleSelectionChange = (row: any) => {
  if (row && row.length) {
    multipleSelection.value = row;
  } else {
    multipleSelection.value = [];
  }
  emit('handleSelectionChange', multipleSelection.value);
};
// 弹窗选择历史工单（保持选择一致）
const dialogConfirmRepeat = (val:any)=>{
  multipleSelection.value = val;
  for (let i of multipleSelection.value) {
    for (let j of state.tableData) {
      if (i.id === j.id) {
        setTimeout(() => {
          multipleTableRef.value!.toggleRowSelection(j, true);
        }, 0);
      }
    }
  }
}
// 清除重复选择
const clearRepeat=()=>{
  multipleTableRef.value!.clearSelection();
}
// 补充信息
const SupplyRef = ref<RefType>();
const onSupply = (val: any) => {
  SupplyRef.value.openDialog(val);
};
// 补充意见提交成功
const onSupplySuccess = () => {
  searchHistory();
};
// 撤销
const orderRevokeRef = ref<RefType>();
const onRevoke = (row: any) => {
  orderRevokeRef.value.openDialog(row);
};
// 撤销提交成功
const onRevokeSuccess = () => {
  searchHistory();
};
// 督办
const orderSuperviseRef = ref<RefType>(); // 工单督办
const onSupervise = (row:any) => {
  orderSuperviseRef.value.openDialog(row);
};
// 督办提交成功
const onSuperviseSuccess = () => {
  // 刷新列表
  searchHistory();
};
const route = useRoute(); // 路由
onMounted(()=>{

})
defineExpose({
  multipleSelection,
  multipleTableRef,
  searchHistory,
  dialogConfirmRepeat,
  clearRepeat
})
</script>

<style scoped lang="scss">

</style>