<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">创建工单</el-button>
            <el-button type="primary" icon="Download">Excel导出</el-button>
            <el-button type="primary" icon="Download">Excel超时导出</el-button>
            <el-button type="primary" icon="Avatar">默认指派</el-button>
            <el-button type="primary" icon="CloseBold">批量打回</el-button>
            <el-button type="primary" icon="Select">批量确定</el-button>
            <el-button type="primary" icon="FolderChecked">批量审核</el-button>
            <el-button type="primary" icon="Pointer">工单指派</el-button>
            <el-button type="primary" icon="User">客服介入</el-button>
            <el-button type="primary" icon="EditPen">钉钉号填写</el-button>
            <el-button type="primary" icon="Stamp">批量完结</el-button>
            <el-button type="primary" icon="Stamp">批量完结审核</el-button>
            <el-button type="primary" icon="Coin">财务入账</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.columnList"
          :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>查看</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
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.columnList"
    v-model="details.columnList"
  ></edittablehead>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import { useStore } from 'vuex';
import {
  processRowPropertyName,
  setNodeHeight,
  downloadXls,
  handleClearTableQuery,
} 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,
  recordList,
  Claimsfield,
  AppealList,
  timeoutList,
  CustomerColumnList,
  MallassignmentColumnList,
  customerserviceColumnList,
} from '@/option/aftersales/vueTvemp.js';
const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const tabValue = ref(0); //菜单激活
const UserPermissions = ref(''); //当前人身份
const PageLoading = ref(true); //页面loading
const Useridentity = {
  Warehouse_customer_service: '仓库客服',
  Headquarters_customer_service: '总部客服',
  Headquarters_Manager: '总部客服经理',
};
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, state = true) => ({
  name,
  label,
  state,
  request: true,
  DataList: [],
  total: 0,
  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(7, '超时未处理'),
  createTabItem(10, '申诉列表'),
]);
// 首页权限配置
const ButtonPermissions = computed(() => {
  // 根据 TabPermissions 的状态，决定每个按钮的显示隐藏逻辑
  switch (TabPermissions.value) {
    case 0: //全部
      return {
        add: true, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        DingTalkNumber: false, //钉钉号填写
        batchFinish: false, //批量完结
        appeal: false, //申诉
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: UserPermissions.value != '仓库客服', //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 1: //处理中
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: UserPermissions.value != '仓库客服', //工单指派
        applyArbitration: UserPermissions.value == '仓库客服', //客服介入
        DingTalkNumber: false, //钉钉号填写
        batchFinish: false, //批量完结
        Batchdetermination: UserPermissions.value != '仓库客服', //批量确定
        appeal: false, //申诉
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 2: //处理完毕
      return {
        add: false, //新增按钮
        batchReject: UserPermissions.value == '总部客服', //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        DingTalkNumber: false, //钉钉号填
        batchFinish: false, //批量完结
        appeal: UserPermissions.value == '仓库客服' && AppealStatusT.value, //申诉
        Batchdetermination: UserPermissions.value == '仓库客服', //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 3: //待处理
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        appeal: false, //申诉
        Batchdetermination: false, //批量确定
        DingTalkNumber: false, //钉钉号填写
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 4: //理赔金额未出
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        appeal: false, //申诉
        DingTalkNumber: false, //钉钉号填写
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 5: //客服介入
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        appeal: false, //申诉
        DingTalkNumber: false, //钉钉号填写
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: UserPermissions.value != '仓库客服', //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 6: //完结
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        DingTalkNumber: UserPermissions.value == '总部客服经理' && !AppealStatusT.value, //钉钉号填写, //钉钉号填写
        appeal: UserPermissions.value == '仓库客服', //申诉
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: UserPermissions.value != '仓库客服' && !AppealStatusT.value, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 7: //超时未处理
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: false, //批量完结
        appeal: false, //申诉
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: true, //超时导出
      };
    case 8: //待回复
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: true, //客服介入
        batchFinish: false, //批量完结
        appeal: false, //申诉
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: false, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 9: //待审核
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: UserPermissions.value != '仓库客服', //批量完结
        appeal: false, //申诉
        Batchdetermination: false, //批量确定
        ManagerConfirmed: UserPermissions.value == '总部客服经理', //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    case 10: //申诉列表
      return {
        add: false, //新增按钮
        batchReject: false, //批量打回
        assignment: false, //工单指派
        applyArbitration: false, //客服介入
        batchFinish: UserPermissions.value != '仓库客服', //批量完结
        appeal: false, //申诉
        Batchdetermination: false, //批量确定
        ManagerConfirmed: UserPermissions.value == '总部客服经理', //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: true, //导出报表
        Timed_outexport: false, //超时导出
      };
    // 其他任何情况下的默认情况
    default:
      return {
        add: false,
        batchReject: false,
        assignment: false,
        applyArbitration: false,
        batchFinish: false,
        appeal: false,
        Batchdetermination: false, //批量确定
        ManagerConfirmed: false, //处理完毕下面的客服经理批量确定
        ArbitrationDetermination: false, //批量完结确定
        Financial_accounting: false, //财务入账
        defaultassignments: false, //默认指派
        export_Report: 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: [],
  /** 列表 */
  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; //关闭搜索
  onLoad();
};
//清空
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(matchingItem, '匹配出来的角色');
};

// 页面初始化请求
const onLoad = () => {};
/**
 *页面初始化函数，包含字典，等必要请求
 */
const PageOnlaod = async () => {
  await Dictionaryrequest();
  Roleverification();
  console.log(Useridentity, 'Useridentity');

  console.log(dictionaries);
};
PageOnlaod();
</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>
