<template>
  <div class="clStyleCss">
    <div class="left">

      <div class="left">
        <el-tabs v-model="activeName" class="demo-tabs h-full">
          <el-tab-pane v-for="(tab, tabIndex) in tabData" :key="tabIndex" :label="tab" :name="tab">
            <div v-if="tab === '工单详情'">
              <div>
                <h3 class="text-lg font-semibold my-4 text-gray-900 border-l-4 border-blue-500 pl-3">
                  工单内容
                </h3>
                <div class="text-lg/7 overflow-y-auto max-h-48">{{ rowData.content || '暂无' }}</div>
                <h3 class="text-lg font-semibold my-4 text-gray-900 border-l-4 border-blue-500 pl-3"
                  v-if="rowData.suggest">
                  干预建议
                </h3>
                <div class="text-lg/7  overflow-y-auto max-h-48" v-if="rowData.suggest">{{ rowData.suggest }}</div>
              </div>
              <div>
                <el-input :disabled="!showInputUpload()" v-model="clInputData" resize="none" :rows="5" type="textarea"
                  :placeholder="placeholder" maxlength="500"></el-input>

                <div class="upload" :style="{ flexDirection: showInputUpload() ? 'row' : 'row-reverse' }">
                  <el-upload v-if="showInputUpload()" :on-success="clUploadSucc" :headers="uploadHeadData"
                    ref="uploadRef" class="upload-demo" :action="`${baseUrl}system/accessories/upload`"
                    :show-file-list="false">
                    <template #trigger>
                      <el-button :icon="Link" text type="primary">添加附件（最多上传5个附件，单个文件最大20M）</el-button>
                    </template>
                  </el-upload>

                  <!-- 综合查询 type === 'zhcx'-->
                  <div v-if="type === 'djb' && workorderstatename === '待交办'">
                    <el-button @click="wjclick" type="primary">完结</el-button>
                  </div>
                  <!-- 我的待处理 -->

                  <div v-if="type === 'wddcl'">
                    <el-button @click="clClick" type="primary">处理</el-button>
                  </div>
                  <!-- 待交办 type === 'djb'-->
                  <!-- 已办待审核 type === 'ybdsh'-->
                  <!-- 已办待回访 type === 'ybdhf'-->
                  <div v-if="type === 'ybdhf'">
                    <el-button @click="huiFangDis = true" type="primary">回访</el-button>
                  </div>
                  <!-- 我的回复 type === 'wdhf'-->
                  <!-- 组内工单 type === 'zngd'-->
                  <!-- 延期审核 type === 'yqsh'-->

                </div>

                <div class="uploadList">
                  <div v-for="(v, i ) in clUploadIds" :key="i" @mouseover="v['showIcon'] = true"
                    @mouseout="v['showIcon'] = false">
                    <el-image :title="v.url.split('/').at(-1) || v.url" v-if="/.(png|jpg|jpeg)$/.test(v.url)"
                      style="width:40px;height:40px" :src="`${baseUrl}${v.url}`"
                      :preview-src-list="[`${baseUrl}${v.url}`]" fit="cover" />

                    <a v-else :href="`${baseUrl}${v.url}`" :title="v.url.split('/').at(-1) || v.url">
                      <el-icon style="width:40px;height:40px">
                        <Document style="width:30px;height:30px" />
                      </el-icon>
                    </a>

                    <el-icon v-if="showInputUpload()" class="closeIcon" v-show="v['showIcon']" @click="deleteImg(v.id)">
                      <CircleCloseFilled />
                    </el-icon>
                  </div>
                </div>
              </div>

            </div>
            <div v-if="tab === '操作日志'" class="overflow-y-auto" style="max-height: calc(100vh - 140px);">
              <div v-for="(log, index) in czRizDatas" :key="index" class="mb-4 pb-4 border-b last:border-0">
                <div class="flex items-center justify-between text-gray-500 mb-2">
                  <div class="flex items-center gap-2">
                    <el-avatar :size="32" :src="log.avatar" />
                    <span>{{ `${log.operatorname} - ${log.operator}` }}</span>
                  </div>
                  <span>{{ log.operationtime }}</span>
                </div>
                <div class="mb-2">{{ log.logcontent }}</div>
                <div v-if="Object.keys(log.fileurl || {}).length" class="mt-2">
                  <!-- <div class="text-gray-500 text-sm mb-2">附件：</div> -->
                  <div class="flex flex-wrap gap-2">
                    <el-button v-for="(key, index) in Object.keys(log.fileurl)" :key="index" link type="primary"
                      class="flex items-center !rounded-button whitespace-nowrap" @click="openFileFn(log)">
                      <el-icon class="mr-1">
                        <Document />
                      </el-icon>
                      {{ log.fileurl[key].split('/').at(-1) }}
                    </el-button>
                  </div>
                </div>
              </div>

            </div>

            <div class="czRizCss hfjlCss overflow-y-auto" v-if="tab === '回访记录'"  style="max-height: calc(100vh - 140px);">
              <div v-for="(record, index) in hfjlDatas" :key="index" class="mb-4 pb-4 border-b last:border-0">
                <div class="flex items-center justify-between text-gray-500 mb-2">
                  <div class="flex items-center gap-2">
                    <el-avatar :size="32" :src="record.avatar" />
                    <span>{{ record.operatorname }} - {{ record.operator }}</span>
                  </div>
                  <span>{{ record.createtime }}</span>
                </div>
                <div v-if="record.content" class="mb-2">{{ record.content }}</div>
                <div v-if="record.result" class="bg-gray-50 p-3 rounded text-gray-600 text-sm mb-2">
                  <div class="text-gray-500 mb-1">回访结果：</div>
                  {{ record.result }}
                </div>
                <div class="flex items-center gap-2 mt-2">
                  <span class="text-gray-500">回访满意度：</span>
                  <el-rate disabled :model-value="getRate(record.myd || 0)"
                    :score-template="getRateText(record.myd || 0)" />
                </div>

              </div>
              <!-- <div v-for="(item, index) in hfjlDatas" :key="index">
                <div>
                  <UserFilled />
                </div>
                <div>
                  <span>{{ item.operatorname }} - {{ item.operator }}</span>
                  <span>{{ item.createtime }}</span>
                  <span>
                    <mini-audio v-if="item.lyurl" style="margin-left:30px;margin-bottom:3px;"
                      :src="item.lyurl"></mini-audio>
                  </span>
                </div>
                <div>
                  <div v-if="item.content" style="white-space: pre-wrap;margin-bottom:5px">回访内容：{{ item.content }}</div>
                  <div v-if="item.result" style="white-space: pre-wrap;margin-bottom:5px">回访结果：{{ item.result }}</div>
                  <div>
                    <el-rate disabled show-score :model-value="getRate(item.myd || 0)"
                      :score-template="getRateText(item.myd || 0)" />
                  </div>
                </div>
              </div> -->
            </div>

            <div class="flex gap-6" v-if="tab === '相关问卷'" style="max-height: calc(100vh - 140px);">
              <!-- 左侧问卷列表 -->
              <div class="w-64 space-y-4 h-full overflow-y-auto" style="max-height: calc(100vh - 140px);">
                <div v-for="survey in surveys" :key="survey.surveyid"
                  class="bg-white border rounded-lg p-4 cursor-pointer hover:border-blue-500"
                  :class="{ 'border-blue-500': currentSurvey?.surveyid === survey.surveyid }"
                  @click="selectSurvey(survey)">
                  <h3 class="text-lg font-medium text-gray-900 mb-2">{{ survey.title }}</h3>
                  <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-2">
                      <span class="text-2xl font-bold text-blue-600">{{ survey.totalScore }}</span>
                      <!-- <div class="px-3 py-1 rounded-full bg-blue-100 text-blue-800 text-sm">{{ survey.yjName }}</div> -->
                      <el-tag :color="survey.yjColor" style="color: aliceblue;">{{ survey.yjName }}</el-tag>
                    </div>
                  </div>
                  <div class="mt-2 text-sm text-gray-500">最近提交：{{ survey.createtime }}</div>
                </div>
              </div>

              <!-- 右侧问卷详情 -->
              <div class="flex-1 bg-gray-50 rounded-lg p-6 h-full overflow-y-auto" style="max-height: calc(100vh - 140px);">
                <template v-if="currentSurvey?.surveyid">
                  <div class="space-y-6">
                    <fillOut :surveyId="currentSurvey.surveyid" :sheetId="currentSurvey.answersheetId" />
                  </div>
                </template>
                <div v-else class="h-full flex items-center justify-center text-gray-500">
                  请选择左侧问卷查看详情
                </div>
              </div>
            </div>

            <div class="hfjlCss" v-if="item === '评价内容'">
              <div style="margin-left: 30px;">
                <span>{{ ordeDetailData.discontent }}</span>
              </div>
              <div style="margin-left: 15px;">
                <el-rate disabled show-score :model-value="ordeDetailData.myd" :score-template="item.mydname" />
              </div>

            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="操作日志" name="操作日志">
            
          </el-tab-pane>

          <el-tab-pane label="回访记录" name="回访记录">
            
          </el-tab-pane>

		      <el-tab-pane label="延期审核" name="延期审核">
            <div class="czRizCss" v-if="item==='延期审核'">
          <div v-for="(item, index) in yqshDatas" :key="index">
            <div>
              <UserFilled />
            </div>
            <div>
              <span>{{ item.createuser }} - {{ item.createby }}</span>
              <span>{{ item.createtime }}</span>
      
              <span style="margin-left: 30px;" v-if="item.result === null">
              <el-button v-if="checkPermi(['workOrderManagement:deferredReview:tongGuo'])" @click="fns['yqsh'].tongGuoFn('' , '通过')" type="primary" size="small" text>通过</el-button>
              <el-button v-if="checkPermi(['workOrderManagement:deferredReview:boHui'])" @click="yuanYinDis = true" type="primary" size="small" text>驳回</el-button>
              </span>
                    </div>
                    <div>
                      <div style="white-space: pre-wrap;margin-bottom:5px;font-size:14px">
              <div v-if="item.result === '通过'">
                <div>申请延期 至 <b><i>{{ item.delaytime }}</i></b></div>
                <div>申请原因：{{ item.delayreason }}</div>
                <br>
                <div style="color:green">通过申请</div> 
              </div>
              <div v-if="item.result === '驳回'">
                <div>申请延期 至 <b><i>{{ item.delaytime }}</i></b></div>
                <div>申请原因：{{ item.delayreason }}</div>
                <br>
                <div>
                  <span style="color:red">驳回申请</span>。原因：{{ item.opinion }} 
                </div> 
              </div>
              <div v-if="item.result === null"> 
                <div>申请延期 至 <b><i>{{ item.delaytime }}</i></b></div>
                <div>申请原因：{{ item.delayreason }}</div>
              </div>
              </div> 
            </div>
          </div>
        </div>
          </el-tab-pane> -->

        </el-tabs>
      </div>
    </div>

    <div class="right">
      <div>
        <h3 class="text-lg font-semibold my-4 text-gray-900 border-l-4 border-blue-500 pl-3">
          工单信息
        </h3>
        <div class="listCss" v-if="firsttypename !== '客户转运'">
          <div>
            <div>工单编号</div>
            <div>{{ rowData.workordercode }}</div>
          </div>
          <div>
            <div>来电号码</div>
            <div>{{ rowData.callnum }}</div>
          </div>
          <div>
            <div>来电人</div>
            <div>{{ rowData.caller }}</div>
          </div>
          <div v-if="firsttypename === '投诉'">
            <div>投诉科室</div>
            <div>{{ rowData.complaintdeptname }}</div>
          </div>
          <div v-if="firsttypename === '投诉'">
            <div>投诉人</div>
            <div>{{ rowData.complaintusername }}</div>
          </div>
          <div>
            <div>工单类型</div>
            <div>{{ rowData.workordercatename }}</div>
          </div>
          <div>
            <div>工单状态</div>
            <div>
              <el-tag v-if="rowData.workorderstatename" effect="plain" :type="tagTypeFn(rowData.workorderstatename)">{{
          rowData.workorderstatename }}</el-tag>
            </div>
          </div>
          <div v-if="rowData.handlingMeasuresName">
            <div>处理措施</div>
            <!-- <div :style="{color: proxy.dicColor('order_handling_measures', rowData.handlingMeasures)}">{{ rowData.handlingMeasuresName }}</div> -->
            <div>{{ rowData.handlingMeasuresName }}</div>
          </div>
          <div>
            <div>创建时间</div>
            <div>{{ rowData.createtime }}</div>
          </div>
          <div>
            <div>办理时限</div>
            <div>{{ rowData.limittime }}</div>
          </div>
          <div>
            <div>年龄</div>
            <div>{{ rowData.age || '未知' }}</div>
          </div>
          <div>
            <div>年龄阶段</div>
            <div>{{ rowData.ageGroup || '未知' }}</div>
          </div>
          <div>
            <div>地址</div>
            <div>{{ rowData.areaName || '未知' }}</div>
          </div>
          <div>
            <div>详细地址</div>
            <div>{{ rowData.address || '未知' }}</div>
          </div>
          <div>
            <div>回访满意度</div>
            <div>
              <el-tag v-if="rowData.mydname" effect="plain" :type="huiFangTagTypeFn(rowData.myd || 0)">{{
          getRateText(rowData.myd || 0)
        }}</el-tag>
            </div>
          </div>

        </div>

        <div class="listCss" v-if="firsttypename === '客户转运'">
          <div>
            <div>工单编号</div>
            <div>{{ ordeDetailData.workordercode }}</div>
          </div>
          <div>
            <div>申请人姓名</div>
            <div>{{ ordeDetailData.caller }}</div>
          </div>
          <div>
            <div>申请人电话</div>
            <div>{{ ordeDetailData.callnum }}</div>
          </div>
          <div>
            <div>工单类型</div>
            <div>{{ ordeDetailData.workordercatename }}</div>
          </div>
          <div>
            <div>工单状态</div>
            <div>
              <el-tag v-if="ordeDetailData.workorderstatename" effect="plain"
                :type="tagTypeFn(ordeDetailData.workorderstatename)">{{
          ordeDetailData.workorderstatename }}</el-tag>
            </div>
          </div>
          <div>
            <div>客户数量</div>
            <div>{{ ordeDetailData.patientnum }}</div>
          </div>
          <div>
            <div>陪护数量</div>
            <div>{{ ordeDetailData.caresnum }}</div>
          </div>
          <div>
            <div>医护数量</div>
            <div>{{ ordeDetailData.doctornum }}</div>
          </div>
          <div>
            <div>目的地</div>
            <div>{{ ordeDetailData.destination }}</div>
          </div>
          <div>
            <div>发车时间</div>
            <div>{{ ordeDetailData.needtime }}</div>
          </div>
          <div>
            <div>车辆类型</div>
            <div>{{ ordeDetailData.cartype == 1 ? '大车' : ordeDetailData.cartype == 2 ? '小车' : '面包车' }}</div>
          </div>
          <div>
            <div>转运说明</div>
            <div>{{ ordeDetailData.remark }}</div>
          </div>
          
          <div>
            <div>创建时间</div>
            <div>{{ ordeDetailData.createtime }}</div>
          </div>

        </div>
      </div>

      <div v-if="firsttypename !== '客户转运'">
        <h3 class="text-lg font-semibold my-4 text-gray-900 border-l-4 border-blue-500 pl-3">
          客户信息
        </h3>
        <div class="listCss">
          <div>
            <div>姓名</div>
            <div>{{ kehuData.name || '-' }}</div>
          </div>
          
          <div>
            <div>电话</div>
            <div>{{ kehuData.phoneNumber && userDecryptToAsterisk(kehuData.phoneNumber) }}</div>
          </div>
          <!-- <div>
            <div>公司</div>
            <div>{{ kehuData.company || '-' }}</div>
          </div> -->
          <div>
            <div>标签</div>
            <div>
              <el-tag style="margin-left: 1px" v-for="(item, index) in kehuData.labellist" :key="index">{{
          item.labelName ||
          '-' }}</el-tag>
            </div>
          </div>
          <div>
            <div>性别</div>
            <div>{{ kehuData.sex !== '0' ? kehuData.sex === '1' ? '男' : '女' : '未知' }}</div>
          </div>
          <!-- <div>
            <div>类型</div>
            <div>{{ kehuData.type === 1 ? '普通' : kehuData.type === 2 ? '微信' : kehuData.type === 3 ? '官网' : '-' }}</div>
          </div>
          <div>
            <div>备注</div>
            <div>{{ kehuData.remarks || '-' }}</div>
          </div> -->


        </div>



      </div>
    </div>

    <!-- 原因 	-->
    <reasonModal v-model:dialogVisible="yuanYinDis" @submit="yuanYinFn" :title="yuanYinTitle"></reasonModal>

    <!-- 交办 -->
    <reassignment v-model:dialogVisible="jiaoBanDis" @submit="jiaoBanFn"></reassignment>

    <!-- 回访 -->
    <returnVisitModal v-model:dialogVisible="huiFangDis" @submit="huiFangFn" :callnum="rowData.callnum">
    </returnVisitModal>

    <!-- 编辑 -->
    <page-modal ref="bianJiRef" :pageName="bianJiUrl" :modalConfig="bianJiModalConfig" :defaultInfo="rowData" title="编辑"
      @submit="bianJiFn"></page-modal>

    <!-- 日志附件图片 -->
    <attachmentList v-model:dialogVisible="fuJianDis" :fileList="fuJianData"></attachmentList>

    <!-- 申请延期 -->
    <postponeModal v-model:dialogVisible="yanQiDis" @submit="fns['wddcl'].yanqiFn"></postponeModal>
  </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, getCurrentInstance } from 'vue';
import { Link, User, Search } from '@element-plus/icons-vue';
import fillOut from '@/views/main/survey/fill.vue';

import reasonModal from '@/components/workOrder/reasonModal';
import returnVisitModal from '@/components/workOrder/returnVisitModal';
import reassignment from '@/components/workOrder/reassignment';
import attachmentList from '@/components/workOrder/attachmentList';
import postponeModal from '@/components/workOrder/postponeModal';
import PageModal from '@/components/page-modal';
import miniAudio from '@/components/audio/audio';
import useTagsViewStore from '@/store/modules/tagsView'
import useSystemStore from '@/store/main/system/system';
import { userDecryptToAsterisk } from '@/utils/aes'

import { checkPermi } from "@/utils/permission";

// 已办待审核 编辑配置
import { tagTypeFn } from '@/utils/index';

import { getToken } from '@/utils/auth';
import {
  getPageListData,
  deletePageData,
  createPageData,
  editPageData,
} from '@/api/main/system/system';

const baseUrl = import.meta.env.VITE_APP_BASE_API;

import { useRoute, useRouter } from 'vue-router';
// const { workordercode , type } = useRoute().query;
const { back, push } = useRouter();
const userRouter = useRouter();
const { proxy } = getCurrentInstance();

let workordercode, type;
if (sessionStorage.getItem('workQuery')) {
  workordercode = JSON.parse(sessionStorage.getItem('workQuery')).workordercode;
  type = JSON.parse(sessionStorage.getItem('workQuery')).type;
  console.log(workordercode, type, 'type');
} else {
  proxy.$modal.msgError('未查找到工单编号，即将返回至综合查询...');

  push({ path: '/workOrderManagement/workOrderList' });
}
const firsttypename = ref('')
const workorderstatename = ref('')

const tabData = ref(['工单详情', '操作日志', '回访记录'])
/*** ------------------------------------------------------------------------------------------------------------------- */

// 处理回复内容
const clInputData = ref('');
// 回复内容提示
const placeholder = ref('请输入，不可超过500字...');

// 处理标签切换
const activeName = ref('工单详情');
// switch (type) {
//   case 'yqsh':
//     activeName.value = '延期审核';
//     break;
//   default:
//     activeName.value = '操作日志';
//     break;
// }

// 本地上传返回的文件, 编辑情况下保存的文件列表
const clUploadIds = ref([]);
// 操作日志数据
const czRizDatas = ref([]);
// 回访记录数据
const hfjlDatas = ref([]);
// 延期审核数据
const yqshDatas = ref([]);
// 客户信息数据
const kehuData = ref({});
// 工单详情数据
const ordeDetailData = ref({});
// 文件上传请求头
const uploadHeadData = ref({ Authorization: `Bearer ${getToken()}` });

// 行数据
const rowData = ref({});

// 原因弹出框
const yuanYinDis = ref(false);
// 原因输入框名字
const yuanYinTitle = ref('原因');

// 交办弹出框
const jiaoBanDis = ref(false);

// 编辑Ref
const bianJiRef = ref('');
// 编辑Url
const bianJiUrl = ref('');

switch (type) {
  case 'djb':
    bianJiUrl.value = '/order/workorder';
    break;
  case 'ybdsh':
    bianJiUrl.value = '/order/workorder';
    break;
  default:
    bianJiUrl.value = '';
    break;
}
// 编辑配置项
const bianJiModalConfig = ref({});
switch (type) {


  default:
    bianJiModalConfig.value = { formItems: [] };
    break;
}

// 回访弹出框
const huiFangDis = ref(false);

// 日志附件弹出框
const fuJianDis = ref(false);
// 日志附件数据
const fuJianData = ref([]);

// 申请延期
const yanQiDis = ref(false);

// 初始化
const init = (() => {
  return (async function fn () {
    await new Promise((ok) => {
      let params = {
        workordercode: workordercode,
        pageNum: 1,
        pageSize: 10,
        listType: 0,
      };
      getPageListData(`/order/workorder`, params).then(({ data }) => {

        if (type === '消息') {
          let obj = {
            待交办: 'djb',
            待处理: 'wddcl',
            待审核: 'ybdsh',
          }
          type = obj[data[0].workorderstatename]
        }
        console.log(data[0], 'data[0]')
        rowData.value = data[0];
        getSurveys();
        ok();

      });
    });

    // 查看详情，显示内容数据
    if (rowData.value.workorderstatename !== '待交办' || type !== 'djb') {
      placeholder.value = '';
      clInputData.value = rowData.value.result || '';
    }
    firsttypename.value = rowData.value.firsttypename
    workorderstatename.value = rowData.value.workorderstatename
    // if (firsttypename.value !== '客户转运') {
    //   tabData.value = ['操作日志', '回访记录']
    // } else {
    //   tabData.value = ['操作日志', '评价内容']
    // }
    console.log(firsttypename.value);
    console.log(workorderstatename.value);
    // 获取工单详情
    getOrderDetail(rowData.value.workordercode);
    // 获取操作日志数据
    getCzriz(rowData.value.workordercode);
    // 获取回访记录数据
    getHfrz(rowData.value.workordercode);
    // 获取回访记录数据
    getYanQiData(rowData.value.workordercode);

    // 获取客户信息
    getKehuData(rowData.value.customerno);

    // 接口内的附件
    fileHx();

    return fn;
  })();
})();
// 获取工单详情
function getOrderDetail (data) {

  // getPageListData(`/order/carworkorder/`+data).then(({ data }) => {
  //   console.log(data);
  //   ordeDetailData.value = data
  // });
}
// 获取操作日志
function getCzriz (data) {
  let params = {
    workordercode: data,
  };

  getPageListData(`/order/workorderoperatelog`, params).then(({ data }) => {
    czRizDatas.value = data;
  });
}

// 获取回访记录
function getHfrz (data) {
  let params = {
    workordercode: data,
  };

  getPageListData(`/order/workordervisitlog`, params).then(({ data }) => {
    hfjlDatas.value = data;
  });
}

// 获取客户信息
function getKehuData (data) {
  getPageListData(`/patient/patient/getdetailbyphone/${data}`).then(({ data }) => {
    if (data) {
      kehuData.value = data;
    }

  });
}

// 获取工单延期审核数据
function getYanQiData (data) {
  let params = {
    workordercode: data
  }

  getPageListData('/order/workorderdelayrecord', params).then(data => {
    yqshDatas.value = data?.data || [];
  })
}

// 上传事件
function clUploadSucc ({ state, data }) {
  if (state === 'success') {
    clUploadIds.value.push({
      id: data.Id,
      url: data.url,
    });
    proxy.$modal.msgSuccess('附件上传成功！');
  }
}

// 图片删除事件
function deleteImg (data) {
  for (let i = 0; i < clUploadIds.value.length; i++) {
    let val = clUploadIds.value[i];
    if (val.id === data) {
      clUploadIds.value.splice(i, 1);
      break;
    }
  }
}

// 回访满意度标签颜色
function huiFangTagTypeFn (data) {
  switch (data) {
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case '满意':
      return 'warning';
    case 3:
      return 'danger';
    default:
      return '';
  }
}
// 回访满意度评分数量
function huiFangRateFn (data) {
  switch (data) {
    case '非常满意':
      return 5;
    case '基本满意':
      return 3;
    case '满意':
      return 4;
    case '不满意':
      return 1;
    default:
      return 0;
  }
}

const getRate = (myd) => {
  // 非常满意1 基本满意2  不满意3
  if (myd === 1) return 5;
  if (myd === 2) return 3;
  if (myd === 3) return 1;
  return 0;
};

const getRateText = (myd) => {
  // 非常满意1 基本满意2  不满意3
  if (myd === 1) return '非常满意';
  if (myd === 2) return '基本满意';
  if (myd === 3) return '不满意';
  return '暂无评价';
}


// 动态切换输入框上传功能
function showInputUpload () {
  if (type === 'wddcl') {
    if (rowData.value.workorderstatename === '待处理') {
      return true;
    }

    return false;
  }

  if (type === 'djb') {
    if (rowData.value.workorderstatename === '待交办') {
      return true;
    }

    return false;
  }

  return false;
}

// 回显接口内的附件
function fileHx () {
  for (let key in rowData.value.fileurl) {
    clUploadIds.value.push({
      id: key,
      url: rowData.value.fileurl[key],
    });
  }
}

// 处理按钮事件
function clClick () {
  if (clInputData.value === '') {
    proxy.$modal.msgError('办结结果不能为空，请输入办结结果');
    return;
  }

  let params = {
    file: clUploadIds.value.map((val) => val.id).join(','),
    workordercode: rowData.value.workordercode,
    result: clInputData.value,
  };
  editPageData('/order/workorder/deal', params).then(({ state }) => {
    if (state === 'success') {
      proxy.$modal.msgSuccess('处理成功！');
      if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
        push({ path: '/workOrderManagement/workOrderList' })
      } else {
        // 关闭当前页面
        useSystemStore().setPageFlag(true)
        useTagsViewStore().delView(userRouter.currentRoute.value);
        // 返回上一页面
        push({
          path: '/workOrderManagement/toBeProcessed',
          query: { listType: 1 },
        })

      }
    }
  });
}

// 完结按钮事件
function wjclick () {
  if (clInputData.value === '') {
    proxy.$modal.msgError('办结结果不能为空，请输入办结结果');
    return;
  }

  let params = {
    code: rowData.value.workordercode,
    reason: clInputData.value,
    file: clUploadIds.value.map((val) => val.id).join(','),
  };

  editPageData(`/order/workorder/end`, params).then(({ state }) => {
    if (state === 'success') {
      proxy.$modal.msgSuccess('完结成功！');
      if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
        push({ path: '/workOrderManagement/workOrderList' })
      } else {
        // 关闭当前页面
        useSystemStore().setPageFlag(true)
        useTagsViewStore().delView(userRouter.currentRoute.value);
        // 返回上一页面
        push({
          path: '/workOrderManagement/workOrderList',
          query: { listType: 0 },
        })
      }
    }
  });
}

const fns = {
  zhcx: {
    // 综合查询
    restartFn (data) {
      createPageData(`/order/workorder/restarts/${rowData.value.workordercode}`, data).then(
        (data) => {
          proxy.$modal.msgSuccess(data.message);
        },
      );
    },
  },
  wddcl: {
    // 我的待处理
    backFn (data) {
      createPageData(`/order/workorder/back/${rowData.value.workordercode}`, data).then(
        (data) => {
          proxy.$modal.msgSuccess(data.message);
        },
      );
    },
    yanqiFn (data) {
      let params = {
        ...data,
        code: rowData.value.workordercode
      }

      createPageData('/order/workorder/delay', params).then((data) => {
        proxy.$modal.msgSuccess(data.message);
        if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
          push({ path: '/workOrderManagement/workOrderList' })
        } else {
          back();
        }
      })
    }
  },
  djb: {
    // 待交办
    jbFn (data) {
      console.log(data);

      let params = {
        code: rowData.value.workordercode,
        ...data,
        dealdept: data.dealdept[data.dealdept.length - 1],
      };

      editPageData('/order/workorder/transfer', params).then((data) => {
        proxy.$modal.msgSuccess(data.message);
      });
    },
    openBjFn () {
      bianJiRef.value.dialogVisible = true;
    },
  },
  ybdsh: {
    // 已办待审核
    jjFn (data = ' ', type) {
      editPageData(`/order/workorder/audit/${rowData.value.workordercode}/${type}`, data).then(
        (data) => {
          proxy.$modal.msgSuccess(data.message);
          if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
            push({ path: '/workOrderManagement/workOrderList' })
          } else {
            back();
          }
        },
      );
    },
    openBjFn () {
      bianJiRef.value.dialogVisible = true;
    },
  },
  ybdhf: {
    // 已办待回访
    thFn (data) {
      createPageData(`/order/workorder/backtoaudit/${rowData.value.workordercode}`, data).then(
        (data) => {
          proxy.$modal.msgSuccess(data.message);
        },
      );
    },
  },
  zngd: {
    // 组内工单
    jdFn (data) {
      createPageData(`/order/workorder/receive/${data.workordercode}`, ' ').then((data) => {
        proxy.$modal.msgSuccess(data.message);
        if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
          push({ path: '/workOrderManagement/workOrderList' })
        } else {
          back();
        }
      });
    },
    thFn (data) {
      createPageData(`/order/workorder/back/${rowData.value.workordercode}`, data).then(
        (data) => {
          proxy.$modal.msgSuccess(data.message);
        },
      );
    },
  },
  yqsh: {
    tongGuoFn (data, type) {
      createPageData('/order/workorder/delayaudit', {
        delayId: rowData.value.delayaudit,
        result: type,
        opinion: data,
      }).then((data) => {
        if (data.state === 'success') {
          proxy.$modal.msgSuccess(data.message)
        } else {
          proxy.$modal.msgError(data.message)
        }

        if (type === '通过') {
          if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
            push({ path: '/workOrderManagement/workOrderList' })
          } else {
            back();
          }
        }
      })
    }
  }
};

// 原因弹出框事件
function yuanYinFn (data) {
  if (type === 'zhcx') {
    // 综合查询
    // 重启
    fns['zhcx'].restartFn(data);
  }

  if (type === 'wddcl') {
    // 我的待处理
    // 退回
    fns['wddcl'].backFn(data);
  }

  if (type === 'djb') {
  }

  if (type === 'ybdsh') {
    // 已办待审核
    // 拒绝
    fns['ybdsh'].jjFn(data, 0);
  }

  if (type === 'ybdhf') {
    // 已办待回访
    // 退回
    fns['ybdhf'].thFn(data);
  }

  if (type === 'wdhf') {
  }

  if (type === 'zngd') {
    // 组内工单
    fns['zngd'].thFn(data);
  }

  if (type === 'yqsh') {
    fns['yqsh'].tongGuoFn(data, '驳回')
  }

  // 重新初始化
  // init.then(data=>{
  // 	data()
  // })

  if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
    push({ path: '/workOrderManagement/workOrderList' })
  } else {
    back();
  }
}

// 交办弹出框事件
function jiaoBanFn (data) {
  if (type === 'zhcx') {
  }

  if (type === 'wddcl') {
  }

  if (type === 'djb') {
    // 待交办
    fns['djb'].jbFn(data);
  }

  if (type === 'ybdsh') {
  }

  if (type === 'ybdhf') {
  }

  if (type === 'wdhf') {
  }

  if (type === 'zngd') {
  }

  // 重新初始化
  // init.then(data=>{
  // 	data()
  // })

  if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
    push({ path: '/workOrderManagement/workOrderList' })
  } else {
    back();
  }
}

// 编辑弹出框事件
function bianJiFn (data) {
  // 重新初始化
  init.then((data) => {
    data();
  });
}

// 回访弹出框事件，电话回访
function huiFangFn (data) {

  let params = {
    code: rowData.value.workordercode,
    isover: rowData.value.isend,
    ...data,
  };
  editPageData(`/order/workorder/visit`, params).then((data) => {
    proxy.$modal.msgSuccess(data.message);

    if (JSON.parse(sessionStorage.getItem('workQuery')).type === '消息') {
      // push({path : '/workOrderManagement/workOrderList'})
      // 关闭当前页面
      useSystemStore().setPageFlag(true)
      // 关闭当前页面
      useTagsViewStore().delView(userRouter.currentRoute.value);
      // 返回上一页面
      push({
        path: '/workOrderManagement/waitForReturnVisit',
        query: { listType: 4 },
      })
    } else {
      // 关闭当前页面
      useSystemStore().setPageFlag(true)
      // 关闭当前页面
      useTagsViewStore().delView(userRouter.currentRoute.value);
      // 返回上一页面
      push({
        path: '/workOrderManagement/waitForReturnVisit',
        query: { listType: 4 },
      })

    }
  });
}

// 日志附件弹出框
function openFileFn (data) {
  fuJianDis.value = true;
  fuJianData.value = [];

  if (data.fileurl) {
    for (const key in data.fileurl) {
      fuJianData.value.push({
        url: data.fileurl[key],
      });
    }
  }
}

const surveys = ref([]);
const currentSurvey = ref(null);

const getSurveys = () => {
  if (!rowData.value.callId) return;
  const params = {
    callid: rowData.value.callId,
    // phone: rowData.value.callnum,
  };

  // if (!params.callid || !params.phone) return;

  getPageListData('/survey/survey/getsurveyinfobycallid', params).then(({ data }) => {
    surveys.value = data;

    if (surveys.value.length > 0) {
      currentSurvey.value = surveys.value[0];
      tabData.value.push('相关问卷')
    }
  })
}



const selectSurvey = (item) => {
  currentSurvey.value = item
}
</script>


<style scoped lang="scss">
.uploadList {
  display: flex;
  column-gap: 10px;
  margin-top: 10px;

  >div {
    border: 1px solid #ccc;
    border-radius: 5px;
    // overflow: hidden;
    width: 45px;
    height: 45px;
    padding: 2px;

    position: relative;

    .closeIcon {
      position: absolute;
      top: -10px;
      right: -10px;
      width: 20px;
      height: 20px;
    }
  }
}

.clStyleCss {
  width: 100%;
  height: calc(100vh - 84px);

  display: grid;
  grid-template-columns: minmax(500px, 80%) minmax(300px, 20%);
  grid-template-rows: 100%;
  justify-content: space-evenly;
  overflow: hidden;

  background-color: rgb(211, 217, 231);

  >div {
    background-color: #fff;
    margin: 5px;
    border-radius: 5px;
  }

  .left {
    display: grid;
    grid-template-rows: auto auto 1fr;
    align-content: start;

    padding: 10px;
    padding-left: 15px;

    // height: 100vh;
    >div:nth-of-type(1) {
      h2 {
        // font-weight: 700 !important;
      }
    }

    >div:nth-of-type(2) {
      margin-top: 20px;

      .el-upload {
        .el-button {
          padding: 0;
        }
      }

      >.upload {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 5px;
      }
    }

    .el-tabs__content {
      height: 100%;
    }

    >div:nth-child(3) {
      overflow: hidden;

      ::v-deep .el-tabs__content,
      .el-tab-pane,
      .el-tabs {
        height: 100%;
      }

      .czRizCss {
        height: 100%;
        overflow: auto;
        padding-right: 10px;
        padding-bottom: 60px;

        >div {
          display: grid;
          grid-template-columns: 60px 1fr;
          grid-template-rows: 30px minmax(30px, auto);
          align-items: center;
          column-gap: 10px;
          margin-bottom: 20px;

          >div:nth-child(1) {
            justify-self: center;
            grid-row: span 2;

            display: flex;
            justify-content: center;
            align-items: center;

            width: 48px;
            height: 48px;
            background-color: rgb(240, 150, 77);
            border-radius: 50px;

            svg {
              width: 30px;
              height: 30px;
              color: #fff;
            }
          }

          >div:nth-child(2) {
            >span:nth-child(1) {
              font-size: 16px;
              font-weight: 700;
              color: rgb(106, 142, 248);
              margin-right: 10px;
            }

            >span:nth-child(2) {
              font-size: 12px;
              color: rgb(161, 161, 161);
            }
          }
        }
      }

      .hfjlCss {
        >div {
          >div:nth-child(2) {
            display: flex;
            align-items: center;

            audio {
              height: 30px;
              margin-left: 50px;
            }
          }
        }
      }
    }
  }

  .right {
    padding: 5px 20px;

    >div {
      margin-bottom: 40px;
    }

    h3 {
      font-size: 19px;
      font-weight: 600;
    }

    .listCss {
      margin-left: 10px;
      margin-top: 20px;

      >div {
        display: grid;
        grid-template-columns: 70px 1fr;
        font-size: 13px;
        font-weight: 500;
        margin-bottom: 10px;
        align-items: center;

        >div:nth-child(1) {
          justify-self: left;
          color: rgb(172, 172, 172);
        }
      }
    }
  }
}
</style>