<template>
  <basic-container v-loading="PageLoading" element-loading-text="数据正在加载中...">
    <!-- 首页表格 -->
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="el-fr-d">
          <!-- 查询按钮 -->
          <el-form-item class="el-btn">
            <el-button type="primary" icon="el-icon-search" @click="searchChange">搜 索</el-button>
            <el-button icon="el-icon-delete" @click="searchReset()">清 空</el-button>
          </el-form-item>
          <el-form-item label="配送日期">
            <el-date-picker
              v-model="TopQuery.time"
              type="datetimerange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              :default-time="defaultTime2"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-tabs type="border-card" v-model="tabValue" @tab-change="tabChenge" class="el_tabs">
        <div></div>
        <template v-for="item in TabList">
          <el-tab-pane v-if="item.state" :name="item.name" :label="item.label" :key="item.name">
          </el-tab-pane>
        </template>
      </el-tabs>
      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="Edit" v-if="ButtonPermissions.add">创建工单</el-button>
            <el-button type="primary" icon="Download" v-if="ButtonPermissions.export_Report"
              >Excel导出</el-button
            >
            <el-button type="primary" icon="Download" v-if="ButtonPermissions.Timed_outexport"
              >Excel超时导出</el-button
            >
            <el-button type="primary" icon="Avatar" v-if="ButtonPermissions.defaultassignments"
              >默认指派</el-button
            >
            <el-button type="primary" icon="CloseBold" v-if="ButtonPermissions.batchReject"
              >结果批量打回</el-button
            >
            <el-button type="primary" icon="FolderChecked" v-if="ButtonPermissions.ManagerConfirmed"
              >完结批量审核</el-button
            >
            <el-button type="primary" icon="Select" v-if="ButtonPermissions.Batchdetermination"
              >批量确定</el-button
            >
            <el-button type="primary" icon="Stamp" v-if="ButtonPermissions.Result_review"
              >结果批量审核</el-button
            >
            <el-button type="primary" icon="Pointer" v-if="ButtonPermissions.assignment"
              >工单指派</el-button
            >
            <el-button type="primary" icon="User" v-if="ButtonPermissions.applyArbitration"
              >客服介入</el-button
            >
            <el-button type="primary" icon="EditPen" v-if="ButtonPermissions.DingTalkNumber"
              >钉钉号填写</el-button
            >
            <el-button type="primary" icon="Stamp" v-if="ButtonPermissions.batchFinish"
              >批量完结</el-button
            >
            <el-button type="primary" icon="Stamp" v-if="ButtonPermissions.ArbitrationDetermination"
              >批量完结审核</el-button
            >
            <el-button type="primary" icon="Coin" v-if="ButtonPermissions.Financial_accounting"
              >财务入账</el-button
            >
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="el-icon-refresh" @click="searchChangeS" circle></el-button>
            <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
            <el-button icon="Search" @click="searchHide" circle></el-button>
          </div>
        </div>
      </el-row>

      <!-- 首页表格 -->
      <el-row>
        <!-- 列表模块 -->
        <tablecmt
          class="tableNode"
          :columnList="details.columnListPublic"
          :tableData="data"
          :loading="loadingObj.list"
          @inputTxt="inputsc"
          @timeCheck="timesc"
          @selectCheck="selectsc"
          @selection="selectionChange"
        >
          <template #default="slotProps">
            <template v-if="slotProps.scope.column.label === '异常工单号'">
              <el-text class="el_textBtn" @click="InformationViewing(slotProps.scope)">
                {{
                  slotProps.scope.column.label === '异常工单号'
                    ? slotProps.scope.row.workOrderNumber
                    : ''
                }}
              </el-text>
            </template>

            <template v-if="slotProps.scope.column.label === '操作'">
              <el-text>查看</el-text>
            </template>
          </template>
        </tablecmt>
      </el-row>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div></div>
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.currentPage"
            :page-sizes="[30, 50, 80, 120]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </el-row>
    </div>
  </basic-container>
  <!-- 列表配置显示 -->
  <edittablehead
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.columnListPublic"
    v-model="details.columnListPublic"
    :columnListName="columnListName"
  ></edittablehead>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import { useStore } from 'vuex';
import {
  processRowPropertyName,
  setNodeHeight,
  downloadXls,
  handleClearTableQuery,
  deepClone,
} from '@/utils/util';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getDictionaryBiz } from '@/api/system/dict';
import dayjs from 'dayjs';
import {
  $_getList,
  $_submit,
  $_getDetail,
  $_remove,
  $_getProcessor,
  $_AddReply,
  $_getExchangeList,
  $_getInfo,
  $_batchReturn,
  $_assignCustomerService,
  $_getCustomerServicePersonnel,
  $_arbitrate,
  $_addCompletionEnd,
  $_appealSubmit,
  $_listSettlement,
  $_listAppeal,
  $_listOwn,
  $_moneyUpdate,
  $_updateWorkList,
  $_updateManagerConfirmed,
  $_updateWorkOrderStatus,
  $_AppealDetails,
  $_Cancelappeal,
  $_getDetails,
  $_settlementUpdate,
  $_updateArbitrateStatu,
  $_exportAftersalesWorkOrder,
  $_aftersalesCustomerMall,
  $_aftersalesCustomerMallremove,
  $_aftersalesCustomerMallsave,
  $_aftersalesCustomerMallsetDefault,
  $_updateFinanceTime,
  $_basicdataTripartiteMall,
  $_aftersalesCustomerMallgetByClientId,
  $_exportaftersalesOvertimeFine,
} from '@/api/aftersales/aftersalesWorkOrder';
import {
  columnList,
  columnList1,
  columnList2,
  columnList3,
  columnList4,
  columnList5,
  columnList6,
  columnList7,
  columnList8,
  columnList9,
  columnList10,
  recordList,
  Claimsfield,
  AppealList,
  timeoutList,
  CustomerColumnList,
  MallassignmentColumnList,
  customerserviceColumnList,
} from '@/option/aftersales/vueTvemp.js';
// (0, '全部'),
// (8, '待回复'),
// (3, '待处理(新建)'),
// (1, '处理中'),
// (4, '理赔金额未出'),
// (2, '处理完毕'),
// (5, '客服介入'),
// (9, '待审核'),
// (6, '完结'),
// (10, '申诉列表'),
// (7, '超时未处理'),

const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const tabValue = ref(0); //菜单激活
const UserPermissions = ref(''); //当前人身份
const workOrderStatus = ref(30); //工单状态
const PageLoading = ref(false); //页面loading
const columnListName = ref('columnList');
/**
 * 人身份
 * Warehouse_customer_service  仓库客服
 * Headquarters_customer_service  总部客服
 * Headquarters_Manager 总部客服经理
 */
const Useridentity = {
  Warehouse_customer_service: '仓库客服',
  Headquarters_customer_service: '总部客服',
  Headquarters_Manager: '总部客服经理',
};
const TabPermissions = ref(0); //记录的菜单编号
const TopQuery = ref({
  time: [],
});
// 必要初始化字典
const dictionaries = {
  pc_work_order: ref([]), ////异常类型
  pc_discovery_node: ref([]), //发现环节
  work_order_status: ref([]), //工单状态
  after_sales_visits: ref([]), //角色部门
};
// 菜单标签
const createTabItem = (name, label) => ({
  name,
  label,
  state: true,
  DataList: [],
  total: 0,
  request: true, //是否请求
  currentPage: 1,
  pageSize: 50,
});

const TabList = ref([
  createTabItem(0, '全部'),
  createTabItem(8, '待回复'),
  createTabItem(3, '待处理(新建)'),
  createTabItem(1, '处理中'),
  createTabItem(4, '理赔金额未出'),
  createTabItem(2, '处理完毕'),
  createTabItem(5, '客服介入'),
  createTabItem(9, '待审核'),
  createTabItem(6, '完结'),
  createTabItem(10, '申诉列表'),
  createTabItem(7, '超时未处理'),
]);

const ButtonPermissions = computed(() => {
  // 根据 TabPermissions 的状态，决定每个按钮的显示隐藏逻辑
  switch (TabPermissions.value) {
    case 0: //全部
      return {
        add: true, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        DingTalkNumber: false, //钉钉号填写
        batchFinish: false, //批量完结
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Result_review: false, //结果审核（总部审核处理结果）
        Financial_accounting: false, //财务入账
        defaultassignments: UserPermissions.value != Useridentity.Warehouse_customer_service, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 1: //处理中
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: UserPermissions.value != Useridentity.Warehouse_customer_service, //工单指派
        applyArbitration: UserPermissions.value == Useridentity.Warehouse_customer_service, //客服介入
        DingTalkNumber: false, //钉钉号填写
        batchFinish: false, //批量完结
        Batchdetermination: false, //处理结果批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        Result_review: UserPermissions.value == Useridentity.Headquarters_customer_service, //结果审核（总部审核处理结果）
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 2: //处理完毕
      return {
        add: false, //新增按钮
        batchReject: UserPermissions.value == Useridentity.Headquarters_customer_service, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        DingTalkNumber: false, //钉钉号填
        batchFinish: UserPermissions.value != Useridentity.Warehouse_customer_service, //批量完结
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Result_review: false, //结果审核（总部审核处理结果）
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 3: //待处理
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        Batchdetermination: false, //批量确定
        DingTalkNumber: false, //钉钉号填写
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Result_review: false, //结果审核（总部审核处理结果）
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 4: //理赔金额未出
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        DingTalkNumber: false, //钉钉号填写
        Batchdetermination: UserPermissions.value == Useridentity.Warehouse_customer_service, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        Result_review: false, //结果审核（总部审核处理结果）
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 5: //客服介入
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        DingTalkNumber: false, //钉钉号填写
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: UserPermissions.value != Useridentity.Warehouse_customer_service, //批量总裁完结确定
        Financial_accounting: false, //财务入账
        Result_review: false, //结果审核（总部审核处理结果）
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 6: //完结
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        DingTalkNumber: UserPermissions.value != Useridentity.Warehouse_customer_service, //钉钉号填写, //钉钉号填写
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: UserPermissions.value != Useridentity.Warehouse_customer_service, //财务入账
        defaultassignments: false, //默认指派
        Result_review: false, //结果审核（总部审核处理结果）
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 7: //超时未处理
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Result_review: false, //结果审核（总部审核处理结果）
        Timed_outexport: true, //超时导出
      };
    case 8: //待回复
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: true, //客服介入
        batchFinish: false, //批量完结
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Result_review: false, //结果审核（总部审核处理结果）
        Timed_outexport: false, //超时导出
      };
    case 9: //待审核
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        Batchdetermination: false, //批量确定
        ManagerConfirmed: UserPermissions.value == Useridentity.Headquarters_Manager, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Result_review: false, //结果审核（总部审核处理结果）
        Timed_outexport: false, //超时导出
      };
    // 其他任何情况下的默认情况
    default:
      return {
        add: false,
        batchReject: false,
        assignment: false,
        applyArbitration: false,
        batchFinish: false,
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Result_review: false, //结果审核（总部审核处理结果）
        Timed_outexport: false, //超时导出
      };
  }
});
const details = reactive({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  defaultTime2: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)], // '12:00:00', '08:00:00'
  /** 时间快捷选择设置 */
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ],
  /** 时间选择器数据 */
  stockupDate: [],
  /** 列表 */
  columnListPublic: deepClone(columnList), //公共列表
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    packageListLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    currentPage: 1,
    pageSize: 50,
    total: 0,
  },

  /** 弹出层显示 */
  popUpShow: {
    /** 包件明细 */
    packageOrderListlVisited: false,
    /** 二维码 */
    QRCodeVisible: false,
    /** 修改客户信息 */
    editClientInfoVisible: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 包明细 */
    packageOrderListlVisited: false,
  },
});

const {
  search,
  query,
  shortcuts,
  stockupDate,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
  zeroAdditionalRecordingInfo,
  popUpShow,
  recorddata,
  defaultTime2,
} = toRefs(details);

/** 展开列表控件 */
const showdrawer = _flag => {
  details.drawerShow = _flag;
};
/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  onLoad();
};

/** 表格表头时间选择 */
const timesc = (index, row) => {
  console.log(index, row);
  if (!!index) {
    index = dayjs(index).format('YYYY-MM-DD');
  }
  details.query[row.prop] = index;
  if (!index) {
    delete details.query[row.prop];
  }
  onLoad();
};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  onLoad();
};
/** 表格表头复选框选择 */
const selectionChange = list => {
  console.log(list);
  details.selectionList = list;
};
// 网页顶部搜索按钮
const searchChange = () => {
  onLoad();
};
// 每页多少条
const sizeChange = val => {
  details.page.pageSize = val;
  onLoad();
};
/** 页码改变执行的回调 */
const currentChange = val => {
  details.page.currentPage = val;
  onLoad();
};
// 刷新按钮
const searchChangeS = () => {
  details.search = false; //关闭搜索
  Publicaccessdata();
};
//清空
const searchReset = () => {
  details.query = {};
  details.page.currentPage = 1;
  handleClearTableQuery(details.columnList);
  onLoad();
};
// 顶部搜索
const searchHide = () => {
  console.log(details);
  details.search = !details.search;
  autoscaling();
};
// 字典公共函数
async function updateDictionary(targetArray, dictionaryType) {
  await getDictionaryBiz(dictionaryType).then(res => {
    console.log(res, '字典');
    res.data.data.forEach(item => {
      targetArray.push({
        value: item.dictKey,
        label: item.dictValue,
      });
    });
  });
}
//表格自适应高度
const autoscaling = () => {
  const _node = document.querySelector('.tableNode');
  setNodeHeight(_node, '', true);
};

/**
 * 描述: 初始化字典，包含角色信息、异常类型、发现环节、工单状态，。
 */
const Dictionaryrequest = async () => {
  // Map 生成一个包含所有 Promise 的数组
  const dictionaryPromises = Object.entries(dictionaries).map(([key, refValue]) => {
    return updateDictionary(refValue.value, key);
  });
  //等待字典请求完成执行页面其余参数防止出现判断错误
  await Promise.all(dictionaryPromises);
};

/**
 * 描述: 获取用户角色信息并更新界面元素状态。
 * 该函数用于检查用户的角色，并根据角色执行相应的验证和UI更新逻辑。
 */
const Roleverification = () => {
  const userInfo = localStorage.getItem('TWMS-userInfo');
  if (!userInfo) {
    console.error('用户信息未找到');
    return;
  }
  let roleNames = [];
  try {
    roleNames = JSON.parse(userInfo).content.role_name.split(',');
  } catch (error) {
    console.error('解析用户角色信息出错:', error);
    return;
  }
  // 匹配用户角色
  const matchingItem = dictionaries.after_sales_visits.value.find(item =>
    roleNames.includes(item.label)
  );
  // 更新用户权限
  if (matchingItem) {
    UserPermissions.value = matchingItem.label;
  }
  // 更新TabList的状态
  const updateTabState = (tabName, condition) => {
    const tab = TabList.value.find(res => res.name == tabName);
    if (tab) {
      tab.state = condition;
    }
  };
  if (UserPermissions.value) {
    updateTabState('8', UserPermissions.value == Useridentity.Warehouse_customer_service);
    updateTabState('9', UserPermissions.value == Useridentity.Headquarters_Manager);
  } else {
    // 匹配不到角色时，默认为关闭状态(总部经理的审核菜单)
    updateTabState('9', false);
  }
  console.log('内部执行完毕');
  console.log(matchingItem, '匹配出来的角色');
};

// 页面初始化请求
const onLoad = () => {};
/**
 *页面初始化函数，包含字典，等必要请求
 */
const PageOnlaod = async () => {
  PageLoading.value = true;
  try {
    await Dictionaryrequest(); //初始化字典
    await Roleverification(); //获取角色信息
    tabChenge(TabPermissions.value); //获取页面数据
  } catch (error) {
    console.log(error);
  }

  PageLoading.value = false;
  console.log(Useridentity, 'Useridentity');
  console.log('外部执行完毕');
  console.log(dictionaries);
};
// 页面初始化
PageOnlaod();
/**
 *  @description: 点击tabBar时，记录当前点击的tab
 *  @param {number} value  当前点击的tab的value
 *  @return {void} 无返回值
 */
const tabChenge = async value => {
  try {
    PageLoading.value = true; // 开启loading
    TabPermissions.value = value; // 记录当前点击的菜单
    console.log(tabValue.value, 'tabValue');

    await Processingworkorderstatus(value); // 处理工单状态
    await MenuHeaderProcessing(value); // 处理头部菜单

    // 定义一个异步函数映射表
    const dataProcessingMap = {
      0: Publicaccessdata,
      1: Publicaccessdata,
      2: Publicaccessdata,
      3: Publicaccessdata,
      4: ClaimAmountData,
      5: Publicaccessdata,
      6: Publicaccessdata,
      7: OverdueUnprocessedData,
      8: DataAwaitingReplyData,
      9: Publicaccessdata,
      10: AppealData,
    };

    // 执行对应的函数
    const processDataFn = dataProcessingMap[value] || Publicaccessdata;
    await processDataFn(); // 使用await确保完成
  } catch (error) {
    console.error('An error occurred:', error);
  } finally {
    PageLoading.value = false; // 确保关闭loading
  }
};

/**
 *  @description: 菜单状态处理
 *  @param {number} value  当前点击的tab的value
 *  @return {void} 无返回值
 */
const Processingworkorderstatus = value => {
  switch (value) {
    case 0: // 全部
      workOrderStatus.value = UserPermissions.value === Useridentity.Warehouse_customer_service ? 1000 : null;
      break;
    case 1: // 处理中
      workOrderStatus.value = UserPermissions.value === Useridentity.Warehouse_customer_service ? 20 : 40;
      break;
    case 2: // 处理完毕
      workOrderStatus.value = 30;
      break;
    case 3: // 待处理
      workOrderStatus.value = 10;
      break;
    case 5: // 客服介入
      workOrderStatus.value = 70;
      break;
    case 6: // 完结
      workOrderStatus.value = 90;
      break;
    case 9: // 待审核
      workOrderStatus.value = UserPermissions.value ===  Useridentity.Headquarters_Manager? 500 : null;
      break;
    default:
      workOrderStatus.value = null;
      break;
  }
};

// 公共菜单数据处理
const PublicDataProcessing = data => {
  details.data = data.records;
  console.log(TabList.value, 'TabList');
  let _Obj = {};
  _Obj = TabList.value.find(res => res.name == TabPermissions.value);
  console.log(_Obj, '匹配出来的公共菜单');
  _Obj.DataList = data.records; //数据
  _Obj.total = data.total; //总条数
  _Obj.currentPage = data.current; //当前页
  _Obj.pageSize = data.size; //每页条数
  if (_Obj.DataList?.length) {
    _Obj.request = true;
  } else {
    _Obj.request = false;
  }
};

/**
 *  @description: 菜单表头处理
 *  @param {number} value  当前点击的tab的value
 *  @return {void} 无返回值
 */
const MenuHeaderProcessing = value => {
  const columnLists = {
    columnList, // 0: 全部
    columnList1, // 1: 处理中
    columnList2, // 2: 处理完毕
    columnList3, // 3: 待处理
    columnList4, // 4: 理赔金额未出
    columnList5, // 5: 客服介入
    columnList6, // 6: 完结
    columnList7, // 7: 超时未处理
    columnList8, // 8: 待回复
    columnList9, // 9: 待审核
    columnList10, // 10: 申诉列表
  };

  const keys = Object.keys(columnLists);
  const selectedKey = value >= 0 && value < keys.length ? keys[value] : 'columnList';

  // 使用深拷贝赋值
  details.columnListPublic = deepClone(columnLists[selectedKey]);

  // 将变量名字符串赋值给 columnListName.value
  columnListName.value = selectedKey;

  console.log(details.columnListPublic, 'details.columnListPublic');
  console.log(columnListName.value, 'columnListName.value');
};
// 状态处理
const DataStateProcessing = data => {
  console.log(data, '状态处理');
  console.log(dictionaries, 'dictionaries.pc_work_order.value');

  // 函数用于查找标签
  const findLabelByValue = (collection, value) => {
    const entry = collection.find(res => res.value === value);
    return entry ? entry.label : '/';
  };

  // 对状态进行处理
  if (data.records?.length) {
    data.records.forEach(item => {
      // 处理工单类型
      item.workOrderTypeNameS = findLabelByValue(
        dictionaries.pc_work_order.value,
        item.workOrderType
      );

      // 处理发现节点
      item.discoveryNodeNameS = findLabelByValue(
        dictionaries.pc_discovery_node.value,
        item.discoveryNode
      );

      // 处理工单状态
      item.workOrderStatusNameS = findLabelByValue(
        dictionaries.work_order_status.value,
        item.workOrderStatus
      );
    });
  }
};

/**
 *  @description: 对数据进行处理
 *  @return {void} 无返回值
 */
const DataAndStateProcessing = data => {
  PublicDataProcessing(data); //处理数据
  DataStateProcessing(data); //状态处理
};

/**
 *  @description: 待回复菜单数据请求
 *  @return {Object} 包含待回复菜单数据的对象
 */
const DataAwaitingReplyData = async () => {
  try {
    let _submitData = {
      current: details.page.currentPage, //页码
      size: details.page.pageSize, //条数
    };
    let _res = await $_getProcessor(_submitData);
    console.log(_res, '待回复菜单数据请求');
    const { code, data } = _res.data;
    console.log(data, 'data');
    console.log(code, 'code');
    if (code !== 200) {
      return;
    }
    DataAndStateProcessing(data); //对数据和状态处理
  } catch (error) {
    console.log(error);
  } finally {
  }
};

/**
 *  @description: 理赔金额未出菜单数据请求
 *  @return {Object} 包含待回复菜单数据的对象
 */
const ClaimAmountData = async () => {
  try {
    let _submitData = {
      current: details.page.currentPage, //页码
      size: details.page.pageSize, //条数
    };
    let _res = await $_listSettlement(_submitData);
    console.log(_res, '理赔金额未出菜单数据请求');
    const { code, data } = _res.data;
    console.log(data, 'data');
    console.log(code, 'code');
    if (code !== 200) {
      return;
    }
    DataAndStateProcessing(data); //对数据和状态处理
  } catch (error) {
    console.log(error);
  } finally {
  }
};
/**
 *  @description: 申诉菜单数据请求
 *  @return {Object} 包含申诉菜单数据的对象
 */
const AppealData = async () => {
  try {
    let _submitData = {
      current: details.page.currentPage, //页码
      size: details.page.pageSize, //条数
    };
    let _res = await $_listAppeal(_submitData);
    console.log(_res, '申诉列表菜单数据请求');
    const { code, data } = _res.data;
    console.log(data, 'data');
    console.log(code, 'code');
    if (code !== 200) {
      return;
    }
    DataAndStateProcessing(data); //对数据和状态处理
  } catch (error) {
    console.log(error);
  } finally {
  }
};
/**
 *  @description: 超时未处理菜单数据请求
 *  @return {Object} 包含超时未处理菜单数据的对象
 */
const OverdueUnprocessedData = async () => {
  try {
    let _submitData = {
      current: details.page.currentPage, //页码
      size: details.page.pageSize, //条数
    };
    let _res = await $_listOwn(_submitData);
    console.log(_res, '超时未处理表菜单数据请求');
    const { code, data } = _res.data;
    console.log(data, 'data');
    console.log(code, 'code');
    if (code !== 200) {
      return;
    }
    DataAndStateProcessing(data); //对数据和状态处理
  } catch (error) {
    console.log(error);
  } finally {
  }
};
/**
 *  @description: 公共数据请求，包含全部、待处理、处理中、处理完毕、客服介入、待审核、完结
 */
const Publicaccessdata = async () => {
  try {
    let _submitData = {
      workOrderStatus: workOrderStatus.value, //工单状态
      current: details.page.currentPage, //页码
      size: details.page.pageSize, //条数
    };
    let _res = await $_getList(_submitData);
    const { code, data } = _res.data;
    console.log(data, 'data');
    console.log(code, 'code');
    if (code !== 200) {
      return;
    }
    DataAndStateProcessing(data); //对数据和状态处理
    console.log(_res, '公共数据菜单=:' + TabPermissions.value);
  } catch (error) {
    console.log(error);
  } finally {
  }
};

// 异常工单号点击查看
const InformationViewing = val => {
  console.log(val, '当前行数据');
  const workOrderInfoPath = '/aftersales/aftersalesWorkOrderInfo';
  const queryParams = {
    id: val.row.workOrderId,
    name: `${val.row.workOrderNumber}-信息查看`,
    warehouseId: val.row.warehouseId,
    workOrderNumber: val.row.workOrderNumber,
    businessId: val.row.businessId,
    RouteIndexs: TabPermissions.value,
    workOrderStatus: val.row.workOrderStatus,
  };
  $router.push({ path: workOrderInfoPath, query: { ...queryParams, id: val.row.id } });
};
</script>

<style scoped lang="scss">
:deep(.el-card) {
  height: 100%;
}
:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 !important;
}
.el-fy {
  flex: 1;
  display: flex;
  align-items: flex-end;
}
.avue-crud {
  height: 100%;
  display: flex;
  flex-direction: column;
}
:deep(.el_tabs) {
  .el-tabs__item {
    font-family: '黑体';
    border-right: 1px dashed #00000014;
  }
  .is-active {
    font-family: '黑体';
    font-weight: bold;
  }
  .el-tabs__content {
    display: none;
  }
}
.avue-crud__header {
  min-height: initial;
  margin: 4px 0;
  padding: 0 4px;
}
.avue-crud__left {
  .el-button {
    border-radius: 2px;
  }
}
</style>
