<template>
  <el-card class="box-card" v-loading="Pageloading" element-loading-text="Loading...">
    <div class="contemtMax">
      <div class="left">
        <el-tabs type="border-card" class="topClass" v-model="identifying">
          <el-tab-pane label="订单信息" :name="1"></el-tab-pane>
          <el-tab-pane label="零担信息" :name="2"></el-tab-pane>
        </el-tabs>

        <el-form :model="endFrom">
          <div class="el_top">
            <el-form-item label="异常类型" class="el_inputTop">
              <el-select v-model="endFrom.workOrderType" disabled>
                <el-option
                  v-for="item in IndexException"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="发现节点" class="el_inputTop">
              <el-select v-model="endFrom.discoveryNode" disabled>
                <el-option
                  v-for="item in DiscoveringNodes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="异常工单号" class="el_inputTop el_Workordernumber">
              <el-input
                v-model="endFrom.workOrderNumber"
                disabled
                :placeholder="endFrom.workOrderNumber ? endFrom.workOrderNumber : '暂未生成工单号'"
                clearable
              />
            </el-form-item>
          </div>
          <el-tabs type="border-card" class="PackageInformation">
            <el-tab-pane label="包件信息">
              <div class="ResponsibilityBoxS">
                <div class="el_btbox" v-for="(item, index) in PackageInfo" :key="index">
                  <div class="leftbox">
                    <el-form-item label="包条码">
                      <el-tooltip :content="item.packageCode" placement="top">
                        <el-input v-model="item.packageCode" disabled />
                      </el-tooltip>
                    </el-form-item>

                    <el-form-item label="运单号">
                      <el-tooltip :content="item.waybillNumber" placement="top">
                        <el-input v-model="item.waybillNumber" disabled />
                      </el-tooltip>
                    </el-form-item>

                    <el-form-item label="订单自编码">
                      <el-tooltip :content="item.orderCode" placement="top">
                        <el-input v-model="item.orderCode" disabled />
                      </el-tooltip>
                    </el-form-item>

                    <el-form-item label="一级品">
                      <el-input v-model="item.first" disabled />
                    </el-form-item>

                    <el-form-item label="二级品">
                      <el-input v-model="item.secondary" disabled />
                    </el-form-item>

                    <el-form-item label="品牌">
                      <el-input v-model="item.brandName" disabled />
                    </el-form-item>
                  </div>
                </div>
                <div class="NumTotal">
                  <span>总件数:{{ PackageInfo.length }}</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>

          <el-tabs type="border-card" class="Basic_information">
            <el-tab-pane label="基础信息">
              <div class="el_information">
                <div class="el_information_row">
                  <el-form-item label="车次号" v-if="displaySettings.trainNumber">
                    <el-tooltip :content="endFrom.trainNumber" placement="top">
                      <el-input v-model="endFrom.trainNumber" disabled />
                    </el-tooltip>
                  </el-form-item>

                  <el-form-item label="配送时间" v-if="displaySettings.deliveryTime">
                    <el-date-picker
                      v-model="endFrom.deliveryTime"
                      type="datetime"
                      format="YYYY-MM-DD"
                      disabled
                    />
                  </el-form-item>

                  <el-form-item
                    label="配送司机"
                    prop="deliveryDriver"
                    v-if="displaySettings.deliveryDriver"
                  >
                    <el-select
                      v-model="endFrom.deliveryDriver"
                      filterable
                      default-first-option
                      :reserve-keyword="false"
                      disabled
                    >
                      <el-option
                        v-for="item in DeliveryDriver"
                        :key="item.value"
                        :label="item.driverName + '-' + item.trainNumber"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="车辆路线" v-if="displaySettings.vehicleRoute">
                    <el-input v-model="endFrom.vehicleRoute" disabled />
                  </el-form-item>

                  <el-form-item label="发货时间" v-if="displaySettings.deliverGoodsTime">
                    <el-date-picker
                      v-model="endFrom.deliverGoodsTime"
                      type="datetime"
                      format="YYYY-MM-DD"
                      disabled
                    />
                  </el-form-item>

                  <el-form-item label="发现时间" v-if="displaySettings.discoveryTime">
                    <el-date-picker
                      v-model="endFrom.discoveryTime"
                      type="datetime"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      disabled
                    />
                  </el-form-item>

                  <el-form-item label="入库时间" v-if="displaySettings.warehousingTime">
                    <el-date-picker
                      v-model="endFrom.warehousingTime"
                      type="datetime"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      disabled
                    />
                  </el-form-item>
                  <!-- 必填 -->
                  <el-form-item label="运单商场" v-if="displaySettings.waybillMall">
                    <el-input v-model="endFrom.waybillMall" disabled />
                  </el-form-item>

                  <el-form-item label="合作模式" v-if="displaySettings.typeServiceName">
                    <el-input
                      v-model="endFrom.typeServiceName"
                      :placeholder="
                        endFrom.typeServiceName ? endFrom.typeServiceName : '暂未查询到合作模式'
                      "
                      disabled
                    />
                  </el-form-item>

                <!-- 干线卸车  -->
                  <el-form-item
                    label="责任方"
                    class="processor_box"
                    style="width: 42%"
                    v-if="displaySettings.processorEntityList"
                  >
                    <el-select
                      v-model="endFrom.processorEntityList"
                      placeholder="请选择责任方"
                      disabled
                      multiple
                      filterable
                      clearable
                    >
                      <el-option
                        v-for="item in warehouseData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>


                  <el-form-item
                    class="processor_box"
                    label="处理方"
                    v-if="displaySettings.processor"
                    style="width: 42%"
                  >
                    <el-select
                      v-model="endFrom.processor"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      :reserve-keyword="false"
                      disabled
                    >
                      <el-option
                        v-for="item in warehouseData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    style="min-width: 100%"
                    label="调查经过"
                    v-if="displaySettings.investigationProcess"
                  >
                    <el-input v-model="endFrom.typeServiceName" disabled />
                  </el-form-item>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>

          <el-tabs type="border-card" class="Responsible_box" v-if="FangAddList.length">
            <el-tab-pane label="责任方信息">
              <div class="ResponsibilityBox">
                <div></div>
                <div class="el_btbox" v-for="(item, index) in FangAddList" :key="index">
                  <div class="leftbox">
                    <div class="maxBox">
                      <span class="title">责任方:</span>
                      <!-- 提货环节  -->
                      <el-select
                        v-model="item.businessName"
                        clearable
                        placeholder="请选提货择责任方"
                        v-if="groundlineType == 1"
                        disabled
                      >
                        <el-option
                          v-for="item in responsible"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>

                      <el-select
                        v-else
                        v-model="item.businessName"
                        filterable
                        disabled
                        placeholder="请选择责任方"
                        @change="ResponsiblePartychange(item.businessName, index)"
                      >
                        <el-option
                          v-for="item in warehouseData"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </div>

                    <div class="maxBox">
                      <span class="title">责任人：</span>
                      <el-select
                        v-model="item.personResponsibleName"
                        clearable
                        filterable
                        placeholder="请选责任人"
                        disabled
                        @change="personResponsiblechange(item.personResponsibleName, index)"
                      >
                        <el-option
                          v-for="item in personResponsibleList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </div>
                    <div class="maxBox">
                      <span class="title">责任占比:</span>
                      <el-input
                        v-model="item.responsibilityRatio"
                        placeholder="请输入占比 "
                        clearable
                        :rows="2"
                        disabled
                        @input="ProportionInput"
                      />
                    </div>
                    <div class="maxBox">
                      <span class="title">三方责任人:</span>
                      <el-input v-model="item.tripartite" disabled />
                    </div>
                    <div class="maxBox" style="flex: 1">
                      <span class="title">说明:</span>
                      <el-input
                        v-model="item.description"
                        placeholder="请输入说明 "
                        clearable
                        :rows="2"
                        disabled
                      />
                    </div>
                  </div>
                </div>
                <div class="Proportion">
                  <span class="title">公司占比:{{ companyProportion }}%</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <!-- 处理结果 -->
          <div class="Improveinformation">
            <div class="selector">
              <div class="el-form-item selector">
                <el-tabs type="border-card" style="width: 100%">
                  <el-tab-pane label="处理结果">
                    <el-select
                      v-model="endFrom.result"
                      multiple
                      filterable
                      default-first-option
                      :reserve-keyword="false"
                      placeholder="请选择处理结果"
                      @change="changeProcessingResults"
                    >
                    
                    <!-- :disabled="$route.query.RouteIndexs == '0' || $route.query.RouteIndexs == '2'" -->
                      <el-option
                        v-for="item in ProcessingResults"
                        :key="item.dictKey"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      />
                    </el-select>

                    <div class="ProcessingResults" v-if="ProcessingList.length">
                      <div class="title">处理结果-理赔金额</div>
                      <!-- 处理结果循环列表 -->
                      <div class="el_Processingresults">
                        <template v-for="(item, index) in ProcessingList" :key="index + item.title">
                          <div class="el_Processingresults_box">
                            <span class="el_title">{{ item.title }}</span>
                            <div class="el_Processingresults_box_list">
                              <el-form-item label="金额">
                                <el-input-number
                                  v-model="item.money"
                                  :min="0"
                                  :controls="false"
                                  :value-on-clear="0"
                                  :precision="2"
                                  @change="Totalamount"
                                  :disabled="$route.query.RouterState == 'end'"
                                />
                              </el-form-item>

                              <el-form-item label="支付单位">
                                <el-input
                                  v-model="item.paymentUnit"
                                  placeholder="请输入支付单位"
                                  clearable
                                  :disabled="$route.query.RouterState == 'end'"
                                />
                              </el-form-item>
                              <el-form-item label="理赔支付时间">
                                <el-date-picker
                                  v-model="item.compensationTime"
                                  type="datetime"
                                  format="YYYY-MM-DD"
                                  value-format="YYYY-MM-DD HH:mm:ss"
                                  placeholder="理赔支付时间"
                                  size="default"
                                  :disabled="$route.query.RouterState == 'end'"
                                />
                              </el-form-item>
                              <el-form-item label="支付方式">
                                <el-select
                                  v-model="item.compensationMethod"
                                  placeholder="请选择支付方式"
                                  style="width: 100%"
                                  clearable
                                  :disabled="$route.query.RouterState == 'end'"
                                >
                                  <el-option
                                    v-for="items in item.Paymentmethod"
                                    :key="items.value"
                                    :label="items.label"
                                    :value="items.value"
                                  />
                                </el-select>
                              </el-form-item>
                            </div>
                          </div>
                        </template>
                      </div>

                      <!-- 处理结果说明  -->
                      <el-form-item label="处理结果说明" class="el_resj">
                        <el-input
                          v-model="endFrom.resultDescription"
                          placeholder="请输入处理结果说明"
                          clearable
                          :autosize="{ minRows: 3, maxRows: 4 }"
                          type="textarea"
                        />
                        
                        <!-- :disabled="$route.query.RouteIndexs == '0' || $route.query.RouteIndexs == '2'" -->
                      </el-form-item>
                      <div class="el_tool">
                        <span>总金额:{{ TotalClaimAmount }}元</span>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>

            <el-tabs type="border-card" class="demo-tabs el-endtabs" v-if="routerState == 'end'">
              <el-tab-pane>
                <template #label>
                  <span class="custom-tabs-label">
                    <el-icon><calendar /></el-icon>
                    <span>完结信息</span>
                  </span>
                </template>

                <div class="el-ckbtn">
                  <el-button type="primary" @click="AddCompensation">添加赔款方</el-button>
                  <el-button type="primary" @click="AddPayee">添加受款方</el-button>
                </div>

                <div class="payanindemnity" v-for="(item, index) in CompensationParty" :key="index">
                  <div style="display: flex">
                    <el-form-item :label="item.state == 0 ? '赔款方' : '受款方'" 
                    >
                      <el-select v-model="item.warehouseId" filterable placeholder="请选择仓库">
                        <el-option
                          v-for="item in warehouseData"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="原因"
                    >
                      <el-input v-model="item.reason" placeholder="请填写原因" />
                    </el-form-item>
                  
                    <el-form-item label="金额(元)"
                    >
                      <el-input-number
                        v-model="item.num"
                        :min="0"
                        :controls="false"
                        :value-on-clear="0"
                        :precision="2"
                        @change="amountMoney"
                      />
                    </el-form-item>

                    <el-form-item label="责任人" v-if="item.state == 0"
                    >
                      <el-input
                        v-model="item.compensationPersonnel"
                        placeholder="请填写责任人"
                        clearable
                        :rows="2"
                      />
                    </el-form-item>
                  </div>
                  <div style="display: flex">
                    <div class="el_cwBtn">
                      <!-- <el-button
                        type="primary"
                        v-if="item.state == 0 && UserPermissions != '职能客服' && item.accounting!='1'"
                        @click="accountingBtn(item)"
                      >
                        财务处理
                      </el-button> -->
                      <el-button type="primary" @click="payremove(item.state, index)">
                        移除
                      </el-button>
                    </div>
                  </div>
                </div>
                <div class="paySum">
                  <span>
                    <el-icon><Coin /></el-icon>赔款金额总和:<b>{{
                      TotalamountCompensation
                    }}</b></span
                  >
                  <span>
                    <el-icon><Coin /></el-icon>受款金额总和:<b>{{ TotalamountReceived }}</b></span
                  >
                </div>
              </el-tab-pane>
            </el-tabs>

            <!-- 仲裁原因说明 -->
            <div class="arbitrate" v-if="routerState == 'end'">
              <el-tabs type="border-card" class="demo-tabs">
                <el-tab-pane>
                  <template #label>
                    <span class="custom-tabs-label">
                      <el-icon><calendar /></el-icon>
                      <span>仲裁原因</span>
                    </span>
                  </template>

                  <el-input
                    v-model="endFrom.arbitrate"
                    type="textarea"
                    :autosize="{ minRows: 5, maxRows: 4 }"
                    placeholder="请输入仲裁原因"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>

            <!-- 图片  -->
            <div class="Transport_damage_photos" v-if="endFrom.packageImage.length">
              <span class="title">照片</span>
              <el-upload
                disabled
                v-model:file-list="endFrom.packageImage"
                list-type="picture-card"
                :on-preview="pictureList"
                :on-remove="ImgListRemove"
                :action="doubledCount"
                :on-success="ImgSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                multiple
                drag
              >
                <el-icon><Plus /></el-icon>
              </el-upload>

              <el-dialog v-model="dialogImgList" width="30%">
                <el-image
                  :src="amplifyurl"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="amplifysrcList"
                  :initial-index="4"
                  fit="cover"
                />
              </el-dialog>
            </div>

            <!-- 视频  -->
            <!-- <div class="Transport_damage_photos void">
              <span class="title">视频</span>
              <el-upload
                class="upload-demo"
                drag
                :action="doubledCount"
                :headers="headers"
                :on-success="ViodSuccess"
                :disabled="$route.query.RouteIndexs == '0'"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  点击上传
                  <span v-if="videoUrl" class="PreviewVoid" @click.stop="Clickviod">点击预览</span>
                </div>
              </el-upload>
            </div> -->

            <!-- 视频预览弹窗 -->
            <el-dialog v-model="VideoPreviewStatus" title="视频预览" width="40%">
              <video height="360" controls class="video-player">
                <source :src="videoUrl" type="video/mp4" />
              </video>
            </el-dialog>
          </div>

          <div class="el_sub">
            <el-button
              v-if="Completepermissions" 
              type="primary"
              class="button"
              @click="submitCompletion"
              >完结提交</el-button
            >
            <el-button
              v-if="$route.query.RouteIndexs != '0' && $route.query.RouterState == 'determine'"
              type="primary"
              class="button"
              @click="submitresults(1)"
              >处理结果提交</el-button
            >
            <el-button
              v-if="$route.query.RouteIndexs != '0' && $route.query.RouterState == 'determine'"
              type="primary"
              class="button"
              @click="submitresults(2)"
              >处理结果保存</el-button
            >
            <!-- <el-button
              @click="DetermineStorage"
              v-if="$route.query.RouteIndexs != '0'"
              type="primary"
              class="button"
              >确定</el-button
            > -->

            <el-button
              v-if="$route.query.workOrderStatus == '10' && UserPermissions != '仓库客服'"
              type="primary"
              class="button"
              @click="CustomerServiceCompleted"
              >客服完结完结</el-button
            >
            <!-- <el-button
              v-if="$route.query.RouteIndexs == '0' && $route.query.workOrderStatus != '21'"
              type="primary"
              class="button"
              @click="ElProcessingResults"
              >处理结果</el-button
            > -->
          </div>
        </el-form>
      </div>

      <el-affix :offset="msgTop">
        <div class="right">
          <el-tabs type="border-card">
            <div class="content">
              <el-tab-pane label="调查记录">
                <div class="el_header-top">
                  <div class="el_Processingparty">
                    <span>回复</span>
                    <el-select
                      v-model="MessageResponsibility"
                      multiple
                      filterable
                      default-first-option
                      :reserve-keyword="false"
                      placeholder="请选择处理方"
                      @change="Msgresponsibility"
                    >
                      <el-option
                        v-for="item in warehouseData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                      />
                    </el-select>
                  </div>

                  <div class="el_Refresh" @click="Chatrefresh">
                    <el-button type="primary">刷新</el-button>
                  </div>
                </div>
                <div class="ovhe" :style="{ height: msgHight + 'px' }" ref="scrollContainer">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(item, index) in MessageContent"
                      :key="index"
                      placement="top"
                    >
                      <el-card>
                        <div class="header-top">
                          <div class="e_ico">
                            <el-icon><User /></el-icon>:
                            <h4>{{ item.username }}【{{ item.name }}】</h4>
                          </div>
                          <div class="e_ico e_time">
                            <h4>{{ item.time }}</h4>
                          </div>
                          <el-tag
                            :class="{
                              identifyingC1: item.difference == '1',
                              identifyingC2: item.difference == '2',
                              identifyingC3: item.difference == '3',
                              'mx-1': true,
                            }"
                            effect="dark"
                            >{{
                              item.difference == '1'
                                ? ' 调查记录'
                                : item.difference == '2'
                                ? '指定记录'
                                : item.difference == '3'
                                ? '操作记录'
                                : ''
                            }}
                          </el-tag>
                        </div>

                        <div class="e_ico">
                          <el-icon><ChatRound /></el-icon>:<span> {{ item.content }}</span>
                        </div>

                        <div class="img" v-if="item.img">
                          <el-image
                            :src="item.img"
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            :preview-src-list="item.imgList"
                            :initial-index="4"
                            fit="cover"
                          />
                        </div>
                        <div class="mp4" @click="AddVideoPreview(index)" v-if="item.mp4">
                          <span
                            >视频: <el-icon><VideoPlay /></el-icon>点击预览
                          </span>
                        </div>

                        <div class="file" v-if="item.file" @click="FileDownload(index)">
                          <a :href="item.file">
                            <span
                              >文件: <el-icon><FolderOpened /></el-icon> 点击下载
                            </span>
                          </a>
                        </div>
                        <div class="identifying">
                          <!-- <div class="e_ico">
                            <el-icon><Timer /></el-icon>:
                            <p>{{ item.time }}</p>
                          </div> -->
                          <div
                            class="tag"
                            v-if="
                              (msgState == 1 || msgState == 2 || msgState == 3) && item.identifying
                            "
                          >
                            <el-tag class="mx-1" effect="dark"
                              >{{
                                msgState == 1
                                  ? ' 待回复'
                                  : msgState == 2
                                  ? '已回复'
                                  : msgState == 3
                                  ? '已超时'
                                  : ''
                              }}
                            </el-tag>
                          </div>
                        </div>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <!-- 输入框  -->
                <div class="inputMax" v-loading="Msgloadinga" element-loading-text="Loading...">
                  <div class="inputfell">
                    <div class="inputbtn">
                      <div class="inputleft">
                        <el-upload
                          ref="uploadRef"
                          class="upload-demo"
                          :action="doubledCount"
                          :headers="headers"
                          :on-success="fellSuccess"
                        >
                          <template #trigger>
                            <el-button type="primary" class="el-fil">上传附件</el-button>
                            <!-- <div class="felltis" v-if="KFfeel.length">上传成功</div> -->
                          </template>
                        </el-upload>

                        <!-- <el-select
                        v-model="separateMessageResponsibility"
                        multiple
                        filterable
                        default-first-option
                        :reserve-keyword="false"
                        placeholder="指定处理方"
                        @change="Msgresponsibility"
                      >
                        <el-option
                          v-for="item in warehouseData"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          :disabled="item.disabled"
                        />
                      </el-select> -->
                      </div>
                      <el-button type="primary" class="el_next" @click="NextRecord()">
                        下一条
                      </el-button>
                    </div>

                    <el-input
                      v-model="Msgtextarea"
                      :rows="5"
                      type="textarea"
                      placeholder="请输入要回复的内容"
                      @input="appoint(Msgtextarea)"
                    />
                    <div class="msgHf">
                      <!-- <el-button type="primary" @click="replyMessageEnd()"> 结束回复 </el-button> -->
                      <el-button type="primary" @click="replyMessage()"> 回复 </el-button>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="操作记录">
                <div class="ovhe" :style="{ height: msgHight + 'px' }" ref="scrollContainer">
                  <el-timeline style="max-width: 600px">
                    <el-timeline-item timestamp="2018/4/12" placement="top">
                      <el-card>
                        <div>
                          <span>操作人</span>
                          <h4>Update Github template</h4>
                        </div>
                        <div>
                          <span>操作事件</span>
                          <p>Tom committed 2018/4/12 20:46</p>
                        </div>
                      </el-card>
                    </el-timeline-item>
                    <el-timeline-item timestamp="2018/4/3" placement="top">
                      <el-card>
                        <h4>Update Github template</h4>
                        <p>Tom committed 2018/4/3 20:46</p>
                      </el-card>
                    </el-timeline-item>
                    <el-timeline-item timestamp="2018/4/2" placement="top">
                      <el-card>
                        <h4>Update Github template</h4>
                        <p>Tom committed 2018/4/2 20:46</p>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </el-tab-pane>
            </div>

            <!-- <el-tab-pane label="菜单2"></el-tab-pane> -->
          </el-tabs>
        </div>
      </el-affix>
    </div>
    <!-- 支付方式选择 -->
    <el-dialog v-model="ZFdialog" title="支付方式选择" width="45%" class="ZFfsLoad">
      <el-radio-group v-model="endFrom.compensationMethod">
        <el-radio
          :label="item.dictKey"
          v-for="item in Paymentmethod"
          :key="item.dictKey"
          size="large"
          border
          >{{ item.dictValue }}</el-radio
        >
      </el-radio-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ZFdialog = false">取消</el-button>
          <el-button type="primary" @click="PaymentConfirmation(endFrom.compensationMethod)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogHistoricalPackage" title="查看历史包件" width="30%">
      <el-form-item label="历史包件选择">
        <el-select v-model="HistoricalPackageinput" clearable filterable placeholder="请选择包件">
          <el-option
            v-for="item in HistoricalPackageList"
            :key="item.value"
            :label="item.workOrderNumber"
            :value="item.workOrderId"
          />
        </el-select>
        <el-button @click="ViewPackageDetails(HistoricalPackageinput)">查看详情</el-button>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogHistoricalPackage = false">取消</el-button>
          <el-button type="primary" @click="HistoricalPackage(HistoricalPackageinput)">
            确定选择
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 财务处理弹窗 -->
    <!-- 弹出框 -->

    <el-dialog v-model="accountingLodading" title="财务是否处理" width="30%">
      <div class="cw_load">
        <el-radio-group v-model="accountingValue" class="ml-4">
          <el-radio label="1" size="large">已处理</el-radio>
          <el-radio label="2" size="large">未处理</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="accountingLodading = false">取消</el-button>
          <el-button type="primary" @click="accountingFn"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import { getDetailWarehouse, getDeptWarehouse } from '@/api/basicdata/basicdataWarehouse'; //处理方
import {
  $_getInfo,
  $_addSubmit,
  $_addCompletionEnd,
  $_getBusinessDepartmentUser,
  $_savaSurveyRecord,
  $_addProcessingResults,
  $_getSurveyRecord,
  $_getAbnormalPackage,
  $_getTrackRecord,
  $_accounting,
  $_getList,
  $_getProcessor,
  $_updateWorkOrderStatus,
  $_updateManagerConfirmed,
  $_updateProcessingParty,
} from '@/api/aftersales/aftersalesWorkOrder';
import { columnList, recordList } from '@/option/aftersales/vueTvemp.js';
import { getToken } from '@/utils/auth';
import { useRoute, useRouter } from 'vue-router';
import { getDictionaryBiz } from '@/api/system/dict';
import { computeNumber, isNumber, AddressClosed, deepClone } from '@/utils/util';
import { useStore } from 'vuex';
// 获取vuex仓库
const $useStore = useStore();
const identifying = ref(1); //订单类型
const ZFdialog = ref(false); //支付方式弹出
const $route = useRoute();
const $router = useRouter();
const Paymentmethod = ref([]); //支付方式
const ZFname = ref(''); //支付名字预留状态
const routeData = ref(false); //路由参数
const groundlineType = ref(''); //责任方状态
const routerState = ref(''); //路由状态
const TotalamountCompensation = ref(0); //赔款金额合计
const TotalClaimAmount = ref(0); //理赔总金额
const TotalamountReceived = ref(0); //收款金额合计
const personResponsibleList = ref([]); //责任人列表
const msgHight = ref(100); //聊天框消息高度
const msgTop = ref(10); //聊天框吸顶距离
const paymentUnit = ref(''); //支付单位
const scrollContainer = ref(null); //客服实例
const KFfeel = ref([]); //附件链接
const MessageResponsibility = ref([]); //消息的处理方选择
const separateMessageResponsibility = ref([]); //消息的处理方单独选择
const Msgtextarea = ref(''); //回复框消息
const ruleFormRef = ref(null); //表单实例
const msgState = ref(0); //回复消息状态
const Msgloading = ref(false); //消息回复的加载效果
const companyProportion = ref(0); //公司占比
const HistoricalPackageList = ref([]); //历史包件数组
const dialogHistoricalPackage = ref(false); //包件弹窗
const HistoricalPackageinput = ref(''); //历史包件选择
const UserPermissions = ref(''); //操作权限
const accountingLodading = ref(false); //财务是否处理
const accountingValue = ref(''); //财务处理结果
const accountingID = ref(); //财务处理当id前值
const dialogImgList = ref(false); //图片预览弹窗
const amplifyurl = ref(''); //当前点击的图片
const amplifysrcList = ref([]); //图片循环列表
const Replycopy = ref([]); //拷贝一份回复方
const Mydata = ref(); //当前登录人信息
const DiscoveringNodes = ref([]); //发现节点
const IndexException = ref([]); //异常类型
const Pageloading = ref(false); //页面加载load
const userInfo = ref({}); //用户信息
const PackageInfo = ref([
  //包件信息
  { packageCode: '', orderCode: '', waybillNumber: '' },
]);
// 提货责任方
const responsible = ref([
  {
    value: '1',
    label: '工厂',
  },
  {
    value: '2',
    label: '外包搬运',
  },
  {
    value: '3',
    label: '物流',
  },
]);
const endFrom = ref({
  packageImage: [
    //图片
  ],
  videoUrl: {}, //视频
  result: [],
});
const viodUrl = ref({});
const videoUrl = ref(null); //视频预览
const VideoPreviewStatus = ref(false); //视频预览状态
const Paymentmethodoptions = ref([]); //支付方式下拉菜单
const warehouseData = ref([]); //处理方
const MessageContent = ref([]);
const CompensationParty = ref([
  {
    name: '',
    state: 0,
    num: 0,
    reason: '',
    cld: 1,
    warehouseId: null,
    compensationPersonnel: '',
  }, //赔款方
  // explains: ''
  {
    name: '',
    state: 1,
    num: 0,
    reason: '',
    cld: 1,
    warehouseId: null,
    compensationPersonnel: '',
  }, //受款方
  // explains: ''
]); //收/赔
const ProcessingList = ref([]); //处理结果已经选择的列表
// 责任方列表
const FangAddList = ref([
  {
    businessName: '',
    personResponsibleName: '',
    responsibilityRatio: '' + '%',
    description: '',
    tripartite: '',
  },
]);
const TransportlossList = ref([
  //运损发现节点
]); //运损发现节点
const ProcessingResults = ref([]); //处理结果列表选项
// 运损触发事件
const details = reactive({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  /** 时间快捷选择设置 */
  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: deepClone(columnList),

  /** 列表数据 */
  data: [],
  // 处理记录
  recordList: deepClone(recordList),
  // 处理记录数据
  recorddata: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    packageListLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    currentPage: 1,
    pageSize: 5,
    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,
} = toRefs(details);
const TransportChange = val => {
  console.log(val, '运损触发事件');
};
// 字典公共函数
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 onLoad = async () => {
  Pageloading.value = true; //开启页面加载
  if (localStorage.getItem('my_data')) {
    Mydata.value = JSON.parse(localStorage.getItem('my_data')); //获取本地仓库信息
  }
  updateDictionary(IndexException.value, 'pc_work_order'); //异常类型
  updateDictionary(DiscoveringNodes.value, 'pc_discovery_node'); //发现环节
  updateDictionary(Paymentmethodoptions.value, 'payment_method'); //支付方式
  getDictionaryBiz('result_handling').then(res => {
    ProcessingResults.value = res.data.data;
  }); //处理结果
  // 获取角色权限
  getDictionaryBiz('after_sales_visits')
    .then(res => {
      console.log(res, '角色字典');
      const matchingItem = res.data.data.find(
        item =>
          item.dictValue == JSON.parse(localStorage.getItem('TWMS-userInfo')).content.role_name
      );
      if (matchingItem) {
        UserPermissions.value = matchingItem.dictValue;
      } else {
        UserPermissions.value = '仓库客服';
      }
      console.log(UserPermissions.value, '当前角色权限');
      Chathistory(); //聊天的历史记录
      // 获取页面参数
      if ($route.query.id) {
        console.log($route.query);
        routerState.value = $route.query.RouterState; //当前是新增记录
        console.log(routerState.value, '当前状态');
        $_getInfo({ id: $route.query.id }).then(res => {
          console.log(res, '回显返回值参数');
          endFrom.value = res.data.data;
          console.log(endFrom.value, '存储起来的参数');
          endFrom.value.result = [];
          endFrom.value.processor = [];
          endFrom.value.packageImage = [];
   


          //图片处理回显
          if (res.data.data.discoveryNode == '1') {
            groundlineType.value = '1';
          } else {
            groundlineType.value = 'null';
          }
          res.data.data.decreaseImageVOList.forEach(res => {
            amplifysrcList.value.push(res.imagePath);
            endFrom.value['packageImage'].push({
              name: res.imageName,
              url: res.imagePath,
            });
          });
          // 包件回显
          PackageInfo.value = res.data.data.abnormalPackageVOList;
          // 要修改
          // 责任方回显
          FangAddList.value = res.data.data.processorVOList
            .filter(item => item && item.typesOf && item.typesOf === '1')
            .map(item => {
              return { businessName: item.businessId };
            });
           // 干线卸车责任方回显
          if(res.data.data.discoveryNode == '3'){
            endFrom.value.processorEntityList=[]
            res.data.data.processorVOList.forEach(item => {
             if (item) {
                if (item.typesOf == '1') {
                  // 责任方回显
                  endFrom.value.processorEntityList.push(item.businessId);
                } 
              }
             });
          }



          let factorydata = res.data.data.personResponsibleVOS.find(item => item.typesOf);
          if (factorydata &&  factorydata.typesOf) {
            groundlineType.value = true; //切换处理方模式
          }
          FangAddList.value = res.data.data.personResponsibleVOS.map(res => {
            console.log(groundlineType.value, '当前责任方状态');
            return {
              businessName: res.businessName, //责任方ID
              personResponsibleName: res.personResponsibleName, //责任人名称
              responsibilityRatio: res.responsibilityRatio, //占比
              description: res.description, //说明
              tripartite: res.tripartite, //三方责任人
            };
          });

          // 要修改
          res.data.data.processorVOList.forEach(item => {
            if (item) {
              if (item.typesOf == 2 && item.processingStatus == '1') {
                // 处理方
                endFrom.value.processor.push(item.businessId);
                MessageResponsibility.value.push(item.businessId);
                Replycopy.value.push(item.businessId); //拷贝一份要回复的
              }
            }
          });
          console.log(JSON.parse(localStorage.getItem('my_data')).id);
          if (UserPermissions.value == '仓库客服') {
            if (localStorage.getItem('my_data')) {
              MessageResponsibility.value.push(JSON.parse(localStorage.getItem('my_data')).id);
              MessageResponsibility.value = MessageResponsibility.value.filter(
                item => item !== JSON.parse(localStorage.getItem('my_data')).id
              ); //过滤掉当前登录人的仓库
            }
            MessageResponsibility.value = [...new Set(MessageResponsibility.value)]; //对回复方去重
          }

          // 公司占比回显计算
          let sum = 0;
          FangAddList.value.forEach(item => {
            if (item.responsibilityRatio) {
              item.responsibilityRatio = item.responsibilityRatio.replace(/%/g, '');
              sum = Number(item.responsibilityRatio) + sum;
            }
          });
          FangAddList.value.forEach(item => {
            item.responsibilityRatio = item.responsibilityRatio + '%';
          });
          companyProportion.value = 100 - sum;
          // 处理结果回显
          if (res.data.data.processingResultsVO.processingMoneyEntityList) {
            ProcessingList.value = res.data.data.processingResultsVO.processingMoneyEntityList.map(
              item => {
                endFrom.value.result.push(item.resultType);
                return {
                  title: item.resultTypeName, //标题
                  money: Number(item.money), //金额
                  paymentUnit: item.paymentUnit, //支付单位
                  compensationTime: item.compensationTime, //理赔时间
                  compensationMethod: item.compensationMethod, //支付方式Value
                  compensationMethodName: item.compensationMethodName, //支付方式lable
                  resultName: item.resultName, //处理方式lable
                  resultType: item.resultType, //处理方式Value
                  typesOf: 1, //固定参数
                  Paymentmethod: [...JSON.parse(JSON.stringify(Paymentmethodoptions.value))],
                };
              }
            );
          }
          // 总金额回显
          TotalClaimAmount.value = res.data.data.processingResultsVO.money;
          // 处理结果说明回显
          endFrom.value.resultDescription = res.data.data.processingResultsVO.resultDescription;
          // 完结信息回显
          // 受款方

          if (res.data.data.completionRecipientEntityList.length > 0) {
            CompensationParty.value = [];
            res.data.data.completionRecipientEntityList.forEach((item, index) => {
              TotalamountReceived.value += Number(item.money);
              CompensationParty.value.push({
                state: 1, //状态
                num: item.money, //金额
                name: item.recipient, //受款方名字
                reason: item.reasonReceivingPayment, //受款方原因
                cld: index + 1,
                id: item.id,
              });
            });
          }
          // 赔款方
          if (res.data.data.completionRecordEntities.length) {
            res.data.data.completionRecordEntities.forEach((item, index) => {
              TotalamountCompensation.value += Number(item.money);
              CompensationParty.value.push({
                state: 0, //状态
                num: item.money, //金额
                name: item.indemnitor, //受款方名字
                reason: item.reason, //受款方原因
                cld: index + 1,
                id: item.id,
                accounting: item.accounting ? item.accounting : '',
                warehouseId: item.warehouseId, //仓库
                compensationPersonnel: item.compensationPersonnel, //赔款人员
              });
            });
          }
          endFrom.value.arbitrate = res.data.data.reasonArbitration; //完结说明
          Pageloading.value = false;
        });
      }
      console.log(endFrom.value, '表单信息');
      getDeptWarehouse({}).then(res => {
        // 验证本地仓库用于回复选择，自己不能选择自己仓库
        console.log(res, '处理方');
        console.log(localStorage.getItem('WarehouseName'), '当前本地仓库');
        res.data.data.forEach(item => {
          warehouseData.value.push({
            value: item.id,
            label: item.name,
            disabled: item.name == localStorage.getItem('WarehouseName'),
          });
        });
      });
    })
    .catch(error => {
      console.log(error, 'error');
      Pageloading.value = false;
    });
};

// 多开页面的时候刷新参数
watch($route, (to, from) => {
  onLoad();
});

// 文件识别
const Fileidentifier = val => {
  const url = val;
  const fileName = url.substring(url.lastIndexOf('/') + 1);
  const extension = fileName.substring(fileName.lastIndexOf('.') + 1);
  if (extension === 'mp4') {
    return 'mp4';
  }
  if (extension === 'png') {
    return 'png';
  }
  if (extension === 'docx') {
    return 'docx';
  }
  return undefined; // 针对其他扩展名的情况返回 undefined
};
// 聊天记录获取
const Chathistory = res => {
  Msgloading.value = true; //开启加载效果
  MessageResponsibility.value = JSON.parse(JSON.stringify(MessageResponsibility.value)); //清空选择内容
  Msgtextarea.value = ''; //清空输入框消息
  let filetype = ''; //文件类型
  MessageContent.value = []; //先清空内容，防止内容重复叠加
  let resData = null; //用于保存返回值
  if (UserPermissions.value != '仓库客服') {
    console.log(UserPermissions.value, '当前不是仓库客服');
    $_getTrackRecord({
      id: $route.query.id,
    })
      .then(res => {
        console.log(res, 'res调查记录');
        res.data.data.surveyRecordEntities.forEach(item => {
          MessageContent.value.unshift({
            time: item.createTime, //时间
            content: item.processingResults, //消息内容
            name: item.addDepartment, //营业部名称
            username: item.addPeople, //用户名
            img: filetype == 'png' ? item.pictureUrl : '',
            file: filetype == 'docx' ? item.pictureUrl : '',
            mp4: filetype == 'mp4' ? item.pictureUrl : '',
            imgList: [filetype == 'png' ? item.pictureUrl : ''],
            difference: item.difference,
            identifying: false, //待回复标识
          });
        });
        setTimeout(() => {
          const container = scrollContainer.value;
          if (container) {
            container.scrollTop = container.scrollHeight;
          }
        }, 0);
        console.log(res, '聊天记录');
      })
      .catch(error => {
        console.log(error, 'error');
      })
      .finally(res => {
        Msgloading.value = false; //关闭加载效果
      });
  } else {
    $_getSurveyRecord({
      id: $route.query.id,
    }).then(res => {
      console.log(res, '聊天返回值');
      console.log(resData, '处理记录返回值');
      // 仓库客服不需要操作记录
      if (res.data.data.processorVOList) {
        if (res.data.data.processorVOList.length) {
          msgState.value = res.data.data.processorVOList[0].processingStatus; //获取聊天状态
        }
      }
      res.data.data.surveyRecordEntities.forEach(item => {
        if (item.pictureUrl) {
          filetype = Fileidentifier(item.pictureUrl);
        }
        MessageContent.value.push({
          time: item.createTime, //时间
          content: item.content, //消息内容
          name: item.addDepartment, //营业部名称
          username: item.addPeople, //用户名
          img: filetype == 'png' ? item.pictureUrl : '',
          file: filetype == 'docx' ? item.pictureUrl : '',
          mp4: filetype == 'mp4' ? item.pictureUrl : '',
          imgList: [filetype == 'png' ? item.pictureUrl : ''],
          difference: item.difference,
          identifying: true, //是否显示待回复按钮
        });
      });
      setTimeout(() => {
        const container = scrollContainer.value;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      }, 0);
      Msgloading.value = false; //关闭加载效果
      console.log(res, '聊天记录');
    });
  }
};

onLoad();
onMounted(() => {
  msgHight.value = window.innerHeight * 0.76;
  console.log(msgHight.value, '处理好的页面高度');
  msgTop.value = window.innerHeight * 0.1;
  // 滚动到最后
  setTimeout(() => {
    const container = scrollContainer.value;
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  }, 0);
});
// 处理结果事件
const changeProcessingResults = value => {
  // 重置总金额
  TotalClaimAmount.value = 0;
  // 重置循环列表
  ProcessingList.value = [];
  console.log(value, 'value');
  if (value.length) {
    let data = [];
    value.forEach(item => {
      let _data = ProcessingResults.value.find(res => res.dictKey == item);
      if (_data) {
        data.push(_data);
      }
    });
    if (data && data.length) {
      data.forEach(item => {
        ProcessingList.value.push({
          title: item.dictValue, //标题
          money: 0, //金额
          paymentUnit: '', //支付单位
          compensationTime: '', //理赔时间
          compensationMethod: '', //支付方式Value
          compensationMethodName: '', //支付方式lable
          resultName: '', //处理方式lable
          resultType: '', //处理方式Value
          typesOf: 1, //固定参数
          Paymentmethod: [...JSON.parse(JSON.stringify(Paymentmethodoptions.value))],
        });
      });
    }
    console.log(ProcessingList.value, '处理好的值');
  }

  return;
  form.value.Claimamount = [];
  if (data && data.length) {
    data.forEach(item => {
      form.value.Claimamount.push({
        title: item.label, //标题
        money: 0, //金额
        paymentUnit: '', //支付单位
        compensationTime: '', //理赔支付时间
        compensationMethod: '', //支付方式
        Paymentmethod: [...JSON.parse(JSON.stringify(Paymentmethodoptions.value))],
      });
    });
  }

  return;
  // 首先删除取消的项目
  ProcessingList.value = ProcessingList.value.filter(item => val.includes(item.state - 1));
  // 然后添加或保持新的项目
  val.forEach(num => {
    let newItem = {
      input: 0,
      min: 0,
      max: 9999999999999,
      state: num + 1,
      payment: '',
      text: '',
      compensationTime: '',
      paymentUnit: '',
    };
    // 根据num为newItem的name字段赋值
    switch (num) {
      case '1':
        newItem.name = '下补单';
        break;
      case '2':
        newItem.name = '维修/补漆';
        break;
      case '3':
        newItem.name = '客户未要求理赔';
        break;
      case '4':
        newItem.name = '用库存';
        break;
      case '5':
        newItem.name = '赔商家';
        break;
      case '6':
        newItem.name = '赔付运费';
        break;
      case '7':
        newItem.name = '工厂考核';
        break;
      default:
        return;
    }

    // 如果列表中不存在则加入新项目
    if (!ProcessingList.value.some(item => item.state === newItem.state)) {
      ProcessingList.value.push(newItem);
      console.log(`添加：${newItem.name}`);
    }
  });
};

const displaySettings = computed(() => {
  return {
    trainNumber: ['3', '5', '7', '6'].includes(endFrom.value.discoveryNode), //车次号
    deliveryTime: ['5', '7', '6'].includes(endFrom.value.discoveryNode), //配送时间
    deliveryDriver: ['5', '7', '6'].includes(endFrom.value.discoveryNode), //配送司机
    vehicleRoute: ['3'].includes(endFrom.value.discoveryNode), //车辆线路
    deliverGoodsTime: ['2'].includes(endFrom.value.discoveryNode), //发货时间
    warehousingTime: ['4'].includes(endFrom.value.discoveryNode), //入库时间
    discoveryTime: ['4', '5', '6', '7'].includes(endFrom.value.discoveryNode), //发现时间
    processorEntityList: ['3'].includes(endFrom.value.discoveryNode), //干线卸车责任方
    waybillMall: true, //运单商场
    typeServiceName: true, //合作模式
    processor: true, //处理方
    investigationProcess: true, //调查经过
  };
});

//处理方
const ProcessingParty = val => {
  console.log(endFrom.value.processor);
};
// 图片上传必须携带TOKEN
const headers = computed(() => {
  return { 'Blade-Auth': 'Bearer ' + getToken() };
});
// 图片上传接口
const doubledCount = computed(() => {
  return '/api/blade-resource/oss/endpoint/put-file';
});
// 图片上传成功回调函数
const ImgSuccess = (response, uploadFile) => {
  if (response.success == true) {
    console.log(response);
    console.log(endFrom.value['packageImage'], '图片列表');
  }
};

// 附件上传成功
const fellSuccess = (response, uploadFile) => {
  console.log('上船成功');
  console.log(response, uploadFile);
  if (response.data.link) {
    KFfeel.value.push(response.data.link);
    console.log(KFfeel.value, '已经上传的附件地址');
  }
};

// 视频上传成功
const ViodSuccess = response => {
  if (response.success == true) {
    console.log(response, '视频上传成功');
    console.log(videoUrl.value, '预览视频添加前');
    videoUrl.value = response.data.link; //放入预览视频中
    console.log(videoUrl.value, '预览视频添加后');
    viodUrl.value = { nmae: response.data.originalName, url: response.data.link };
    console.log(viodUrl.value, '视频对象');
  }
};
// 上传图片规则
const beforeAvatarUpload = rawFile => {
  if (!/^image\/(png|jpeg|gif)$|^video\/mp4$/.test(rawFile.type)) {
    ElMessage.error('上传格式只支持 png、jpeg、gif 和 mp4 类型!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 40) {
    ElMessage.error('上传大小不能超过 40MB!');
    return false;
  }
  return true;
};
// 点击图片列表回调
const pictureList = val => {
  dialogImgList.value = true;
  amplifyurl.value = val.url;
  console.log(val, '图片列表');
};

// 点击图片移除
const ImgListRemove = val => {
  console.log(val, '移除图片');
};
// 查看已上传视频列表
const Clickviod = () => {
  console.log('点击了预览');
  VideoPreviewStatus.value = true; //开启预览视频弹窗
};
// 添加赔款方
const AddCompensation = () => {
  console.log('添加赔款方');
  let som = 1;
  CompensationParty.value.forEach(item => {
    if (item.state == 0) {
      som++;
    }
  });

  let lastIndex = -1;

  for (let i = CompensationParty.value.length - 1; i >= 0; i--) {
    if (CompensationParty.value[i].state == 0) {
      lastIndex = i;
      break; // 找到匹配元素后中断循环
    }
  }

  if (lastIndex !== -1) {
    CompensationParty.value.splice(lastIndex + 1, 0, {
      name: '',
      state: 0,
      num: 0,
      reason: '',
      cld: som,
      compensationPersonnel: '',
      warehouseId: '',
    });

    // CompensationParty.value.push({
    //   name: '',
    //   state: 0,
    //   num: 0,
    //   reason: '',
    //   cld: som,
    //   compensationPersonnel: '',
    //   warehouseId: '',
    // });
  } else {
    console.log(`在数组中未找到 ${elementToFind}。`);
  }

  // explains: ''
};
// 添加受款方
const AddPayee = () => {
  let som = 1;
  CompensationParty.value.forEach(item => {
    if (item.state == 1) {
      som++;
    }
  });

  let lastIndex = -1;

  for (let i = CompensationParty.value.length - 1; i >= 0; i--) {
    if (CompensationParty.value[i].state == 0) {
      lastIndex = i;
      break; // 找到匹配元素后中断循环
    }
  }

  if (lastIndex !== -1) {
    CompensationParty.value.splice(lastIndex + 1, 0, {
      name: '',
      state: 1,
      num: 0,
      reason: '',
      cld: som,
      compensationPersonnel: '',
      warehouseId: '',
    });
  }
};
// 表单校验
const ruleForm = reactive({
  // warehouseId: [{ required: true, message: '请选择仓库', trigger: ['bulr', 'change'] }],
  // reason: [{ required: true, message: '请输入原因', trigger: ['bulr', 'change'] }],
  // num: [{ required: fal, message: '请输入金额', trigger: ['bulr', 'change'] }],
  // compensationPersonnel: [{ required: true, message: '请连写责任人', trigger: ['bulr', 'change'] }],
});

// 总金额计算
const Totalamount = () => {
  TotalClaimAmount.value = ProcessingList.value
    .map(res => res.money)
    .reduce((accumulator, currentValue) => accumulator + currentValue, 0);
};
// 移除按钮
const payremove = (state, val) => {
  // 判断赔付方，至少保留一条数据

  if (CompensationParty.value.map(res => res.state == 0).length == 1) {
    ElMessage({
      message: '赔款必填最少一条',
      type: 'warning',
    });
    return;
  }
  CompensationParty.value.splice(val, 1);
  for (let i = val; i < CompensationParty.value.length; i++) {
    CompensationParty.value[i].cld = CompensationParty.value[i - 1].cld + 1; // 更新后续对象的id值
  }
  console.log('CompensationParty :>> ', CompensationParty);
  amountMoney();
};
// 公司占比计算
const ProportionInput = val => {
  console.log(FangAddList.value, '公司占比');
  let sum = 0;
  FangAddList.value.forEach(item => {
    sum = Number(item.responsibilityRatio) + sum;
  });
  sum = 100 - sum;
  companyProportion.value = sum;
  console.log(sum, '公司占比');
};
// 完结提交按钮权限
const Completepermissions =computed(()=>{
  if(UserPermissions.value != '仓库客服'){
    if( $route.query.RouteIndexs != '0'){
    if($route.query.RouterState == 'end'){
      return true
    }else{
      return false
    }
  }else{
    return false
  }
  }else{
    return false
  }
})

// 财务处理
const accountingBtn = item => {
  accountingLodading.value = true; //开启财务确定弹窗
  accountingID.value = item.id;
  console.log(accountingID.value, '当前财务处理的ID');
};
const accountingFn = () => {
  let data = {
    id: accountingID.value,
    accounting: accountingValue.value,
  };
  console.log(data, '处理好的值');
  $_accounting(data).then(res => {
    console.log(res, '财务处理');
    accountingLodading.value = false; //关闭财务确定弹窗
    if (res.data.code) {
      ElMessage({
        message: res.data.msg,
        type: 'success',
      });
    }
    onLoad();
  });
};

// 金额输入汇总
const amountMoney = () => {
  // 计算赔款金额总数
  TotalamountCompensation.value = 0;
  TotalamountReceived.value = 0;
  CompensationParty.value.forEach(item => {
    const _num = isNumber(item.num) ? item.num : 0;
    // 统计赔款方【0】
    if (item.state == 0) {
      TotalamountCompensation.value = computeNumber(
        TotalamountCompensation.value,
        '+',
        _num
      ).result;
    }
    // 统计受款方金额【1】
    if (item.state == 1) {
      TotalamountReceived.value = computeNumber(TotalamountReceived.value, '+', _num).result;
    }
  });
};

// 回复消息@事件
const appoint = val => {
  if (val == '@') {
    console.log('触发了指定选择');
  }
};
// 新视频预览
const AddVideoPreview = val => {
  VideoPreviewStatus.value = true; //开启视频查看弹窗
  videoUrl.value = MessageContent.value[val].mp4;
};
const FileDownload = val => {
  console.log(MessageContent.value[val].file, '文件地址');
};
// 责任方添加
const responsibleParty = () => {
  FangAddList.value.push({
    businessName: '',
    personResponsibleName: '',
    responsibilityRatio: '',
    description: '',
  });
};
// 责任移除
const ResponsibilityRemoval = val => {
  FangAddList.value.splice(val, 1); //移除当前点击的按钮
};
// 消息责任方选择
const Msgresponsibility = val => {
  MessageResponsibility.value = val;
  console.log(MessageResponsibility.value, '已经选择的责任方');
};
// 聊天刷新
const Chatrefresh = () => {
  Chathistory();
};
// 获取当前责任方的责任人
const ResponsiblePartychange = (val, index) => {
  console.log(val, '选择的责任方');
  FangAddList.value[index].personResponsibleName = null; //清空当前选择的责任人
  $_getBusinessDepartmentUser({
    warehouseId: val,
  }).then(res => {
    console.log(res, '获取责任人列表');
    personResponsibleList.value = res.data.data;
  });
};
// 责任人选择
const personResponsiblechange = (val, index) => {
  console.log(val, index);
};
// 支付方式选择
const PaymentSelection = val => {
  if ($route.query.RouteIndexs == '0' || $route.query.RouteIndexs == '2') {
    return;
  }
  console.log(val, '支付');
  console.log(Paymentmethod.value);
  if (val.payment) {
    //支付方式回显
    let data = Paymentmethod.value.find(item => item.dictKey == val.payment);
    endFrom.value.compensationMethod = data.dictKey;
  } else {
    endFrom.value.compensationMethod = null; //清空上一次选择
  }
  ZFdialog.value = true; //展开支付方式选择弹窗
  ZFname.value = val.name; //存放的当前点击的名字
};
// 支付方式选择确定
const PaymentConfirmation = val => {
  console.log(val, '支付方式选择确定');
  let data = ProcessingList.value.find(item => item.name == ZFname.value);
  console.log(data, '处理好的');
  data.text = Paymentmethod.value.find(item => item.dictKey == val).dictValue;
  data.payment = val;
  ZFdialog.value = false; //关闭支付方式选择弹窗
  ElMessage({
    message: '支付方式选择成功',
    type: 'success',
  });
  console.log(ProcessingList.value, '选择好的支付列表');
};

// 确定存储
// const DetermineStorage = () => {
//   let data = {
//     assignList: [],
//   };
//   let a = {};
//   a = $route.query.id;
//   data['assignList'].push(a);
//   if (routerState.value == 'end') {
//     $_updateManagerConfirmed(data).then(res => {
//       if (res.data.code == 200) {
//         ElMessage({
//           message: res.data.msg,
//           type: 'success',
//         });
//       }
//       console.log(res, '完结确定');
//     });
//     // 赔款方
//     console.log(data, '处理好的值');
//   } else {
//     console.log(a);
//     console.log(data, '处理好的数据');
//     $_updateWorkOrderStatus(data).then(res => {
//       console.log(res, '确定提交存储');
//       if (res.data.code == 200) {
//         ElMessage({
//           message: res.data.msg,
//           type: 'success',
//         });
//       }
//     });
//   }
// };

// 处理结果提交
const submitresults = async value => {
  if (!endFrom.value.result.length) {
    ElMessage({
      message: `请选择选择处理结果`,
      type: 'warning',
    });
    return;
  }
  let _title = value == 1 ? '提交' : '保存';
  let _message = `注意信息填写正确!点击确定将<span style="color: red;">${_title}处理结果</span>是否继续?`;
  ElMessageBox.confirm(_message, '提示', {
    dangerouslyUseHTMLString: true, //启用此选项以解析 HTML
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 处理结果填写
      let data = {
        resultIdentification: value == 1 ? '1' : '2', //1为直接提交不需要外部确定，2为保存需要外部确定
        aftersalesProcessingResultsDTO: {
          processingMoneyEntityList: [], //处理结果
        },
      };
      console.log(ProcessingResults.value, 'ProcessingResults.value');
      ProcessingList.value.forEach(item => {
        let _DATA = item.Paymentmethod.find(res => res.value == item.compensationMethod);
        data.aftersalesProcessingResultsDTO['processingMoneyEntityList'].push({
          resultType: ProcessingResults.value.find(res => res.dictValue == item.title).dictKey, //赔方式的key
          resultName: item.title, //处理结果名字
          money: item.money, //金额
          compensationMethod: item.compensationMethod, //支付方式Value
          compensationMethodName: _DATA ? _DATA.label : '', //支付方式lable
          compensationTime: item.compensationTime, //支付时间
          paymentUnit: item.paymentUnit, //支付付单位
          typesOf: 1, //固定参数
        });
      });
      // 支付方式拼接
      data.aftersalesProcessingResultsDTO.compensationMethod = data.aftersalesProcessingResultsDTO[
        'processingMoneyEntityList'
      ]
        .map(res => res.compensationMethodName)
        .join(',');
      // 支付单位拼接
      data.aftersalesProcessingResultsDTO.paymentUnit = data.aftersalesProcessingResultsDTO[
        'processingMoneyEntityList'
      ]
        .map(res => res.paymentUnit)
        .join(',');
      //处理结果说明
      (data.aftersalesProcessingResultsDTO.resultDescription = endFrom.value.resultDescription),
        // 赔付方式拼接
        (data.aftersalesProcessingResultsDTO.resultType = data.aftersalesProcessingResultsDTO[
          'processingMoneyEntityList'
        ]
          .map(res => res.resultName)
          .join(','));
      // 总金额
      data.aftersalesProcessingResultsDTO.money = TotalClaimAmount.value;
      //异常工单ID
      data.aftersalesProcessingResultsDTO.workOrderId = $route.query.id;
      //仓库ID
      data.aftersalesProcessingResultsDTO.warehouseId = endFrom.value.warehouseId; //仓库ID
      //工单ID
      data.id = $route.query.id;
      //是否提交到理赔金额未出(点击保存并且金额都为0才执行)
      if (!data.aftersalesProcessingResultsDTO.money && value == '1') {
        let _message = `检测到您<span style="color: red;">未填写金额</span>是否提交到理赔金额未出?`;
        await ElMessageBox.confirm(_message, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            data.claimIdentification = '1';
            ElMessage({
              type: 'success',
              message: '已确定选择',
            });
          })
          .catch(() => {});
      }
      console.log(data, '要提交的参数');
      Pageloading.value = true;
      $_addProcessingResults(data)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage({
              showClose: true,
              message: res.data.msg,
              type: 'success',
            });
            // 传递要刷新的菜单
            $useStore.commit('EDIT_REFRESHITEM', {title: 'aftersalesWorkOrder',status: true,});//要刷新的页面
            $useStore.commit('Customer_Menu',Number($route.query.RouteIndexs));//要刷新的菜单
            $router.push('/aftersales/aftersalesWorkOrder');
            AddressClosed('/aftersales/aftersalesWorkOrderend'); //删除当前页面
          }
        })
        .catch(error => {
          console.log(error, 'error');
        })
        .finally(res => {
          Pageloading.value = false;
        });
    })
    .catch(error => {
      console.log(error, 'error');
    });
};

// 完结信息提交()
const submitCompletion = () => {
  console.log(  CompensationParty.value);
 let _warehouseId= CompensationParty.value.find(res=>!res.warehouseId)
 if(_warehouseId){
  ElMessage({
      message: `有赔款方或受款方仓库未选择`,
      type: 'warning',
    });
    return
 }
  ElMessageBox.confirm('是否提交完结信息?', '完结', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      console.log(CompensationParty.value);
      console.log(CompensationParty.value, 'CompensationParty');
      let info = JSON.parse(JSON.stringify(endFrom.value)); //拷贝要提交的数据
      console.log(info, 'info');
      let data = [
        {
          id: $route.query.id,
          completionRecipientEntities: [], //受款方
          completionRecordEntities: [], //赔款方
          reasonArbitration: endFrom.value.arbitrate, //完结说明
        },
      ];
      console.log(endFrom.value.duty, '责任方');
      console.log('赔款总计金额', TotalamountCompensation.value);
      console.log('收款总计金额', TotalamountReceived.value);
      if( CompensationParty.value.length){
        CompensationParty.value.forEach(item => {
        if (item.state == 0) {
          // 赔款
          data[0]['completionRecordEntities'].push({
            reason: item.reason, //原因
            money: item.num, //金额
            reasonArbitration: endFrom.value.arbitrate, //完结说明
            compensationPersonnel: item.compensationPersonnel, //责任人（手动填写）
            warehouseId: item.warehouseId, //赔款方是那个仓库（传入ID）
            explains: item.reason, //赔款说明
            workOrderId: info.id, //异常工单
          });
        } else {
          // 受款方
          data[0]['completionRecipientEntities'].push({
            reasonReceivingPayment: item.reason, //受款原因
            money:item.num, //金额
            responsibleParty: FangAddList.value
              .map(aItem =>
                warehouseData.value
                  .filter(bItem => bItem.value === aItem.businessName)
                  .map(match => match.label)
                  .join(',')
              )
              .join(','),
            warehouseId: item.warehouseId, //赔款方是那个仓库（传入ID）
            workOrderNumber: info.workOrderNumber, //工单号
            workOrderId: info.id, //异常工单
          });
        }
      });
      }
      console.log(data, '处理好的值');
      // 赔款方
      Pageloading.value = true; //开启页面加载
      $_addCompletionEnd(data)
        .then(res => {
          console.log(res, '完结成功返回值');
          if (res.data.code == 200) {
            ElMessage({
              showClose: true,
              message: res.data.msg,
              type: 'success',
            });

            $useStore.commit('EDIT_REFRESHITEM', {title: 'aftersalesWorkOrder',status: true,});//要刷新的页面
            $useStore.commit('Customer_Menu',Number($route.query.RouteIndexs));//要刷新的菜单
            $router.push('/aftersales/aftersalesWorkOrder');
            AddressClosed('/aftersales/aftersalesWorkOrderend'); //删除当前页面
          }
        })
        .catch(error => {
          Pageloading.value = false; //关闭页面加载
          console.log(error, '提交失败');
        });
    })
    .catch(() => {});
};
// 提交信息
const submitCompletions = async val => {
  return;
  console.log(UserPermissions.value, '当前角色');
  // 完结的逻辑
  // 异常问题描述非必填
  if (routerState.value == 'end') {
    ElMessageBox.confirm('是否提交完结信息?', '完结', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        console.log(CompensationParty.value);
        // let pay = CompensationParty.value.find(item => item.cld == 1);
        // console.log(pay);
        // if (!pay.name || pay.num == null || !pay.reason) {
        //   ElMessage({
        //     message: '请填写赔款方【1】完整信息',
        //     type: 'warning',
        //   });
        //   return;
        // }
        console.log(CompensationParty.value, 'CompensationParty');
        let info = JSON.parse(JSON.stringify(endFrom.value)); //拷贝要提交的数据
        console.log(info, 'info');
        let data = [
          {
            id: $route.query.id,
            completionRecipientEntities: [], //受款方
            completionRecordEntities: [], //赔款方
            reasonArbitration: endFrom.value.arbitrate, //完结说明
          },
        ];
        console.log(endFrom.value.duty, '责任方');
        console.log('赔款总计金额', TotalamountCompensation.value);
        console.log('收款总计金额', TotalamountReceived.value);

        CompensationParty.value.forEach(item => {
          if (item.state == 0) {
            // 赔款
            data[0]['completionRecordEntities'].push({
              // indemnitor: item.name, //赔款方
              reason: item.reason, //原因
              money: Number(item.num), //金额
              reasonArbitration: endFrom.value.arbitrate, //完结说明
              compensationPersonnel: item.compensationPersonnel, //责任人（手动填写）
              warehouseId: item.warehouseId, //赔款方是那个仓库（传入ID）
              explains: item.reason, //赔款说明
              workOrderId: info.id, //异常工单
            });
          } else {
            // 受款方
            data[0]['completionRecipientEntities'].push({
              // recipient: item.name, //受款方
              reasonReceivingPayment: item.reason, //受款原因
              money: Number(item.num), //金额
              responsibleParty: FangAddList.value
                .map(aItem =>
                  warehouseData.value
                    .filter(bItem => bItem.value === aItem.businessName)
                    .map(match => match.label)
                    .join(',')
                )
                .join(','),
              warehouseId: item.warehouseId, //赔款方是那个仓库（传入ID）
              workOrderNumber: info.workOrderNumber, //工单号
              workOrderId: info.id, //异常工单
            });
          }
        });
        console.log(data, '处理好的值');

        // 赔款方
        Pageloading.value = true; //开启页面加载
        $_addCompletionEnd(data)
          .then(res => {
            console.log(res, '完结成功返回值');
            if (res.data.code == 200) {
              ElMessage({
                showClose: true,
                message: res.data.msg,
                type: 'success',
              });
              $router.push('/aftersales/aftersalesWorkOrder');
              AddressClosed('/aftersales/aftersalesWorkOrderend'); //删除当前页面
            }
          })
          .catch(res => {
            Pageloading.value = false; //开启页面加载
            console.log(res, '提交失败');
          });
      })
      .catch(() => {});
  } else {
    if (!endFrom.value.result.length) {
      ElMessage({
        message: `请选择选择处理结果`,
        type: 'warning',
      });
      return;
    }
    // 处理结果填写

    let data = {
      resultIdentification: val == 1 ? '1' : '2', //1为直接提交不需要外部确定，2为保存需要外部确定
      aftersalesProcessingResultsDTO: {
        processingMoneyEntityList: [], //处理结果
      },
      // processingMoneyEntityList: [], //赔付方式
    };
    ProcessingList.value.forEach(item => {
      data.aftersalesProcessingResultsDTO['processingMoneyEntityList'].push({
        resultType: ProcessingResults.value.find(res => res.dictValue == item.title).dictValue, //赔方式的key
        resultName: item.title, //处理结果名字
        money: item.money, //金额
        compensationMethod: item.compensationMethod, //支付方式Value
        compensationMethodName:
          item.Paymentmethod.find(res => res.value == item.compensationMethod).label || '', //支付方式lable
        compensationTime: item.compensationTime, //支付时间
        paymentUnit: item.paymentUnit, //支付付单位
        typesOf: 1, //固定参数
      });
    });
    console.log(data, '要提交的参数');

    return;
    ElMessageBox.confirm('是否进行处理结果操作?', '处理结果', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        data = {
          resultIdentification: val == 1 ? '1' : '2', //1为直接提交不需要外部确定，2为保存需要外部确定
          aftersalesProcessingResultsDTO: {},
          // processingMoneyEntityList: [], //赔付方式
        };
        ProcessingList.value.forEach(() => {
          data['aftersalesProcessingResultsDTO'].push({
            resultType: ProcessingResults.value.find(res => res.dictValue == item.title).dictValue, //赔方式的key
            resultName: item.title, //处理结果名字
            money: item.money, //金额
            compensationMethod: item.compensationMethod, //支付方式Value
            compensationMethodName:
              item.Paymentmethod.find(res => res.value == item.compensationMethod).label || '', //支付方式lable
            compensationTime: item.compensationTime, //支付时间
            paymentUnit: item.paymentUnit, //支付付单位
            typesOf: 1, //固定参数
          });
        });
        console.log(data, '要提交的参数');

        return;
        // 新增记录处理结果
        console.log($route.query.id, '异常ID');
        console.log(ProcessingList.value, 'ProcessingList12312');
        let info = JSON.parse(JSON.stringify(endFrom.value)); //拷贝要提交的数据
        data = {
          resultIdentification: val == 1 ? '1' : '2', //1为直接提交不需要外部确定，2为保存需要外部确定
          aftersalesProcessingResultsDTO: {
            // ...info,
          },
          // processingMoneyEntityList: [], //赔付方式
        };

        // 必须金额为0是提交,并且点了确定才走这个判断
        if (result && val == '1') {
          // 直接提交到理赔金额未出

          await ElMessageBox.confirm('检测到您未填写金额是否提交到理赔金额未出？', 'Warning', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              data.claimIdentification = '1';
              ElMessage({
                type: 'success',
                message: '已确定选择',
              });
            })
            .catch(() => {
              console.log('取消了选择');
            });
        }

        data.id = $route.query.id;
        data.aftersalesProcessingResultsDTO['workOrderId'] = $route.query.id; //异常工单ID
        let sum = 0; //金额总计
        for (let i = 0; i < ProcessingList.value.length; i++) {
          console.log(ProcessingList.value[i].input);
          sum = computeNumber(sum, '+', ProcessingList.value[i].input).result;
        }
        data.aftersalesProcessingResultsDTO.money = sum; //金额汇总

        data.aftersalesProcessingResultsDTO.resultDescription = endFrom.value.resultDescription; //处理结果说明

        console.log(Paymentmethod.value, 'Paymentmethod.value');

        if (ProcessingList.value.every(res => res.text)) {
          data.aftersalesProcessingResultsDTO['compensationMethod'] = ProcessingList.value
            .map(item => item.text)
            .join(',');
        } else {
          data.aftersalesProcessingResultsDTO['compensationMethod'] = '';
        }

        data.aftersalesProcessingResultsDTO.processingMoneyEntityList = ProcessingList.value
          .map(item => {
            console.log(item);
            let match = ProcessingResults.value.find(element => element.dictValue == item.name);
            if (match) {
              let paymentMethodMatch = Paymentmethod.value.find(
                paymentMethod => paymentMethod.dictKey == item.payment
              );
              return {
                resultType: match.dictKey, //赔方式的key
                money: item.input, //金额
                typesOf: 1, //固定参数
                compensationMethod: paymentMethodMatch ? paymentMethodMatch.dictKey : '',
                compensationMethodName: paymentMethodMatch ? paymentMethodMatch.dictValue : '',
                resultName: item.name, //处理结果名字
                compensationTime: item.compensationTime, //赔付时间
                paymentUnit: item.paymentUnit, //赔付单位
              };
            } else {
              return null;
            }
          })
          .filter(item => item !== null);
        // data.aftersalesProcessingResultsDTO.paymentUnit = paymentUnit.value; //支付单位

        // data.aftersalesProcessingResultsDTO.paymentUnit = ProcessingList.value
        //   .map(item => item.paymentUnit)
        //   .join(','); //支付单位

        if (ProcessingList.value.every(res => res.paymentUnit)) {
          data.aftersalesProcessingResultsDTO.paymentUnit = ProcessingList.value
            .map(item => item.paymentUnit)
            .join(','); //支付单位
        } else {
          data.aftersalesProcessingResultsDTO.paymentUnit = '';
        }

        // data.aftersalesProcessingResultsDTO.processingMoneyEntityList = data['processingMoneyEntityList'];
        console.log('走到了这一步');
        data.aftersalesProcessingResultsDTO.workOrderId = $route.query.id; //异常工单ID
        data.aftersalesProcessingResultsDTO['resultType'] = ProcessingList.value
          .map(item => item.name)
          .join(','); //赔款方式
        let imgLink = ''; //存储图片地址
        // 图片处理存在问题
        // if (endFrom.value['packageImage'].length) {
        //   imgLink = endFrom.value['packageImage'].map(item => item.response.data.link).join(','); //图片处理
        // }
        if (videoUrl.value && imgLink) {
          data.aftersalesProcessingResultsDTO['annex'] = videoUrl.value + ',' + imgLink;
        } else {
          data.aftersalesProcessingResultsDTO['annex'] = imgLink;
        }
        delete data.aftersalesProcessingResultsDTO.id; //删除ID字段

        data.aftersalesProcessingResultsDTO.warehouseId = info.warehouseId; //仓库ID
        console.log(data, '处理好的数据');

        Pageloading.value = true; //开启页面加载

        $_addProcessingResults(data)
          .then(res => {
            console.log(res, '提交后的参数');
            if (res.data.code == 200) {
              ElMessage({
                showClose: true,
                message: res.data.msg,
                type: 'success',
              });
              $router.push('/aftersales/aftersalesWorkOrder');
              AddressClosed('/aftersales/aftersalesWorkOrderend'); //删除当前页面
            }
          })
          .catch(res => {
            Pageloading.value = false; //开启页面加载
          });
      })
      .catch(() => {});
  }
};
// 结束回复
const replyMessageEnd = () => {
  const message = `是否确定<span style="color: red;">结束回复</span>?`;
  ElMessageBox.confirm(message, '提示', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ElMessage({
        message: '功能维护中...',
        type: 'warning',
      });
    })
    .catch(() => {});
};
// 消息回复
const replyMessage = () => {
  console.log(endFrom.value, 'endFrom.value');
  console.log(endFrom.value.workOrderType, '类型');
  if (!Msgtextarea.value) {
    ElMessage({
      message: '请输入回复内容',
      type: 'warning',
    });
    return;
  }

  console.log(MessageContent.value, '当前的聊天记录');
  console.log(warehouseData.value, '参数1212312312312312');
  console.log(MessageResponsibility, '责任方');
  console.log(MessageResponsibility.value, '当前处理方信息');
  console.log(separateMessageResponsibility.value);

  if (!MessageResponsibility.value.length && !separateMessageResponsibility.value.length) {
    ElMessage({
      message: '请选择至少一个处理方',
      type: 'warning',
    });
    return;
  }
  let msgData = {
    processorEntityList: [],
  }; //初始化参数
  msgData.surveyRecordDTO = {
    content: Msgtextarea.value, //内容'
    workOrderId: $route.query.id, //工单ID
    pictureUrl: KFfeel.value.join(','), //附件路径
    remark: '', //备注
  };

  msgData.id = $route.query.id; //异常工单ID
  // 责任方处理 MessageResponsibility 已经选择的处理方
  MessageResponsibility.value.forEach(item => {
    msgData['processorEntityList'].push({
      businessName: warehouseData.value.find(obj => obj.value == item).label, //名称
      businessId: warehouseData.value.find(obj => obj.value == item).value, //ID
      workOrderId: $route.query.id, //异常工单ID
      typesOf: 2, //1 责任方 2 处理方
      warehouseId: $route.query.warehouseId, //仓库ID
    });
  });

  console.log(msgData, '处理好的参数');
  $_savaSurveyRecord(msgData).then(res => {
    console.log(res, '消息回复成功');
    if (res.data.code == 200) {
      Chathistory(); //回复消息成功，调用消息刷新显示最新消息
      ElMessage({
        message: res.data.msg,
        type: 'success',
      });
      // 回复成功之后移除自己

      // $_updateProcessingParty({id:}).then(res=>{
      //   console.log(res,'移除自己成功');
      // })
    }
  });
};
// 下一条跳转
const Nextjump = res => {
  if (res.data) {
    if (res.data.data.records.length) {
      let dataInfo = res.data.data.records[0];
      $router.push({
        path: '/aftersales/aftersalesWorkOrderend',
        query: {
          id: dataInfo.id,
          name: dataInfo.workOrderNumber + '-回复',
          businessId: dataInfo.workOrderNumber,
          RouterState: 'determine',
          index: '0',
        },
      });
    }
  }
};

// 处理方数据公共函数
const ProcessingPartyFun = val => {
  let data = {
    ...val,
  };
  data.current = Nextpage.value; //页码
  data.size = 1; //条数
  $_getProcessor(data).then(res => {
    console.log(res, '点击下一条');
    Nextjump(res);
  });
};
// 页面初始化数据
const IndexTable = val => {
  let data = {
    ...val,
  };
  data.current = Nextpage.value; //页码
  data.size = 1; //条数
  $_getList(data).then(res => {
    console.log(res, '点击下一条返回值');
    Nextjump(res);
  });
};
const Nextpage = ref(0);
// 下一条
const NextRecord = () => {
  Nextpage.value++;
  let data = {};
  console.log(UserPermissions.value, '当前登录人身份');
  if (UserPermissions.value == '仓库客服') {
    ProcessingPartyFun(data);
  } else {
    data.workOrderStatus = 50;
    IndexTable(data);
  }
};
// 历史包件里面的查看
const ViewPackageDetails = val => {
  if (!val) {
    ElMessage({
      message: '请选择要查看的数据',
      type: 'warning',
    });
    return;
  }
  console.log(val);
  let info = HistoricalPackageList.value.find(obj => obj.workOrderId == val);
  console.log(info, '筛选的值');
  $router.push({
    path: '/aftersales/aftersalesWorkOrderInfo',
    query: {
      id: info.workOrderId,
      name: info.workOrderId + '-信息查看',
      routerState: 'view',
    },
  });
  dialogHistoricalPackage.value = false; //打开历史包件弹窗
};
// 处理结果跳转按钮
const ElProcessingResults = () => {
  $router.push({
    path: '',
    query: {
      id: $route.query.id,
      name: $route.query.businessId + '-添加异常记录',
      businessId: $route.query.workOrderNumber,
      RouterState: 'determine',
      RouteIndexs: $route.query.RouteIndexs,
    },
  });
  $useStore.commit('DEL_TAG_CURRENT');
};
// 客服完结完结
const CustomerServiceCompleted = () => {
  $router.push({
    path: '/aftersales/aftersalesWorkOrdermodify',
    query: {
      id: $route.query.id,
      name: $route.query.businessId + '-客服完结完结',
      businessId: $route.query.businessId,
      warehouseId: $route.query.warehouseId ? $route.query.warehouseId : '',
      workOrderNumber: $route.query.workOrderNumber,
      RouteIndexs: $route.query.RouteIndexs,
      RouterState: 'Kfend',
      index: '1',
    },
  });
  $useStore.commit('DEL_TAG_CURRENT');
};
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 100%;
  height: 100%;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  :deep(.el-form-item) {
    display: flex;
    margin: 0;
    .el-select {
      width: 100%;
    }
  }
  :deep(.el-form-item__label) {
    justify-content: flex-start;
  }
  :deep(.el-input--prefix) {
    width: 100%;
    height: 100% !important;
  }
}
.el_Transport {
  width: 100%;
}
.DingTalk {
  width: 100%;
}
.selector {
  width: 100%;
  :deep(.el-select) {
    width: 100%;
  }
}
.ProcessingResults {
  width: 100%;
  min-height: 260px;
  border: 1px solid #ccc;
  position: relative;
  padding: 26px;
  box-sizing: border-box;
  margin-top: 3%;
  color: #606266;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-bottom: 16px;
  .title {
    position: absolute;
    top: -20px;
    left: 20px;
    font-size: 26px;
    background-color: #fff;
  }
  .Listadmiration {
    display: flex;
    flex-wrap: wrap;
    margin-top: 26px;
    justify-content: space-between;
    .name {
      display: flex;
      margin-bottom: 20px;
      height: 30px;
      width: 100%;
      justify-content: space-between;
      span {
        display: block;
        width: 140px;
        color: #606266;
        font-size: 16px;
      }
    }
  }

  .lptime,
  .ZFlptime {
    display: flex;
    .name {
      width: 10%;
      color: #606266;
    }
    .el-input {
      width: auto;
    }
    :deep(.el-input--prefix) {
      width: 200px;
    }
  }
  .ZFlptime {
    margin: 10px 0;
  }
}
.notes {
  width: 100%;
  margin-top: 40px;
}
.Transport_damage_photos {
  width: 100%;
  display: flex;
  margin-top: 26px;
  .title {
    width: 100px;
    color: #606266;
    font-size: 14px;
    margin-bottom: 9px;
    display: block;
  }
  :deep(.el-upload-dragger) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.upload-demo {
  width: 100%;
}
.box-card {
  overflow-y: scroll;
}
.void {
  margin-top: 10px;
  :deep(.el-upload-list) {
    display: none;
  }
  .title {
    width: 100px;
  }
}
.PreviewVoid {
  font-weight: bold;
  color: #172e60;
}

.video-player {
  width: 100%;
}
.ProcessingRecords {
  margin-top: 20px;
  .title {
    font-size: 16px;
    color: #606266;
    width: 100px;
  }
  :deep(.custom-tabs-label) {
    display: flex;
    align-items: center;
  }
}
.el-row {
  height: 300px;
}
:deep(.maboxhi) {
  height: 300px !important;
}
.Improveinformation {
  margin-top: 32px;
  width: 100%;

  :deep(.custom-tabs-label) {
    display: flex;
    align-items: center;
  }
  :deep(.selector) {
    margin-bottom: 40px;
    .is-active {
      font-weight: bold;
    }
  }
  .el_pklab {
    width: 50px;
  }

  .el_pkLi {
    width: 96%;
    display: flex;
    justify-content: flex-start;
  }
}
.payanindemnity {
  display: flex;
  align-items: center;
  margin-top: 20px;
  justify-content: space-between;
  .title {
    width: 126px;
    height: 100%;
    display: flex;
    display: block;
    align-items: center;
  }
  .sk_input {
    margin: 0 5px;
    margin-left: 20px;
    width: 20%;
    display: flex;
    span {
      width: 70px;
      font-size: 16px;
      font-weight: 300;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
  }
  .el-button {
    border: none;
  }
  :deep(.el-form-item) {
    margin-right: 8px;
  }
}
.arbitrate {
  width: 100%;
  margin-top: 20px;
}
.ZFname {
  font-size: 16px;
}
.Paymentname {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #bfbfbf;
  margin-left: 2px;
  border-radius: 4px;
  width: 100px;
  font-size: 14px;
  padding: 10px;
  cursor: pointer;
  width: 190px;
  margin: 0 4px;
}
.Paymentname:hover {
  border: 1px solid #172e60;
}
:deep(.ZFfsLoad) {
  .el-radio {
    padding: 0 8px;
  }
  .el-radio-group {
    width: 100%;
    justify-content: center;
    align-items: center;
  }
}
.paySum {
  margin-top: 36px;
  font-size: 14px;
  display: flex;
  span {
    margin-right: 30px;
    display: flex;
    align-items: center;
  }
}
// 数字输入框
:deep(.el-input-number) {
  width: 160px;
}
.contemtMax {
  display: flex;
  justify-content: space-between;

  .left {
    width: 68%;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
  }
  :deep(.el-affix) {
    width: 30% !important;
  }
  .right {
    width: 100%;
    :deep(.el-card__body) {
      padding: 10px !important;
    }
    :deep(.el-timeline) {
      padding: 0;
    }
    .content {
      position: relative;
    }
  }
  :deep(.el-card) {
    box-shadow: -1px -1px 4px 0px #e3e3e3;
    border-top-left-radius: 20px;
    border-bottom: 1px solid #d5d5d563 !important;
    border-right: 1px solid #d5d5d563 !important;
  }
}
.ResponsibilityBox {
  width: 100%;
  display: flex;
  flex-direction: column;
  .leftbox {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .title {
      width: 40px;
    }
    .maxBox {
      margin-right: 10px;
    }
  }
  .maxBox {
    display: flex;
    align-items: center;
    width: 30%;
    .title {
      width: 120px;
      font-size: 14px;
      color: #606266;
    }
    .el-select {
      width: 100%;
    }
  }
  .el-btn {
    margin-left: 5%;
    border: none;
  }
  .el_btbox {
    display: flex;
    margin-top: 10px;

    .maxBox {
      flex-direction: column;
      align-items: flex-start;
      width: 14%;
    }
  }
  .leftbox {
    justify-content: flex-start !important;
    .title {
      width: 80px;
    }
  }
}
.el_dcl {
  display: flex;
  width: 100%;
}
.Proportion {
  font-size: 14px;
  color: #606266;
  margin-top: 30px;
  .title {
    border: 1px solid #ccc;
    padding: 2px 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: max-content;
    color: #000;
  }
}
.el_tool {
  border: 1px solid #ccc;
  padding: 2px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: max-content;
  color: #000;
  margin-top: 10px;
  span {
    font-size: 14px;
  }
}
.msgHf {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  position: absolute;
  right: 0;
  bottom: 0;
  :deep(.el-button) {
  }
}
.ovhe {
  position: relative;
  overflow-y: scroll;
  scroll-behavior: smooth;
  .e_ico {
    display: flex;
    align-items: center;
  }
  .e_time {
    color: #999;
    font-size: 12px;
  }
  .img {
    width: 50px;
    height: 50px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .mp4 {
    margin-top: 2px;
    span {
      display: flex;
      align-items: center;
      vertical-align: bottom;
      cursor: pointer;
    }
  }
  .tag {
    display: flex;
    justify-content: flex-end;
  }
  .file {
    span {
      display: flex;
      align-items: center;
      vertical-align: bottom;
      cursor: pointer;
    }
  }
  .header-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 23px;
    :deep(.el-tag) {
      width: 70px;
    }
  }
}
.inputMax {
  position: absolute;
  bottom: 0;
  left: 0;
}
:deep(.el-timeline) {
  margin-bottom: 120px;
}
.inputMax {
  background-color: #fff;
  display: flex;
  width: 100%;
  justify-content: space-between;
  .inputfell {
    width: 100%;
    .inputbtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      :deep(.upload-demo) {
        width: auto;
        margin-right: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .inputleft {
        display: flex;
        :deep(.el-fil) {
          background-color: #409eff;
          border: none;
        }
      }
      :deep(.el_next) {
        background-color: #409eff;
        border: none;
      }
      :deep(.el_next:hover) {
        background-color: #409eff;
      }
    }
    :deep(.el-textarea) {
      margin-top: 6px;
    }
  }
}
.el_cwBtn {
  width: 8%;
  display: flex;
  justify-content: flex-end;
}
.PackageInformation {
  width: 100%;
  margin-bottom: 10px;
}
.ResponsibilityBoxS {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  justify-content: flex-start;
  .leftbox {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .el-form-item {
      flex-direction: column;
      align-items: flex-start;
      flex: none;
      width: 16.4%;
    }
  }

  .maxBox {
    display: flex;
    align-items: center;
    width: 30%;
    .title {
      width: 140px;
      color: #606266;
      font-size: 14px;
    }
    .el-select {
      width: 100%;
    }
  }
  .el-btn {
    margin-left: 5%;
    border: none;
    display: flex;
  }
  .el_btbox {
    display: flex;
    margin-top: 10px;
  }
}
.NumTotal {
  width: 30%;
  margin-top: 16px;
  display: flex;
  align-items: center;

  span {
    width: 120px;
    font-size: 14px;
    width: 30%;
    margin-top: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 2px 0;
    border: 1px solid #dcdfe6;
  }
}
.el_sub {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 4px 0;
}

.el_lab {
  margin-right: 10px !important;
}
.cw_load {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el_Processingparty {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  box-shadow: -1px 2px 2px 0px #f5f5f5;
  padding: 0 4px;
  box-sizing: border-box;
  border-radius: 4px;
  height: 40px;
  span {
    width: 40px;
  }
  :deep(.el-select) {
    width: 100%;
  }
}
.el-endtabs {
  margin-top: 26px;
}
.el_PaymentUnit {
  display: flex;
  align-items: center;
  span {
    display: flex;
    width: 80px !important;
    align-items: center;
  }
  :deep(.el-input) {
    width: 150px;
  }
}
.identifying {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 23px;
  .el-tag {
    width: 70px;
  }
}
.identifyingC1 {
  background-color: #409eff;
  border: none;
}
.identifyingC2 {
  background-color: #10d070;
  border: none;
}
.identifyingC3 {
  background-color: #d3832a;
  border: none;
}
.el_header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.Transport_damage_photos) {
  .el-upload {
    display: none;
  }
}
:deep(.topClass) {
  border-bottom: none;

  .el-tabs__content {
    padding: 0;
  }

  .is-active {
    font-weight: bold;
  }
}
.el_top {
  width: 100%;
  padding: 6px;
  display: flex;
  justify-content: space-between;
  :deep(.el-form-item) {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: auto;
  }
}
:deep(.el_resj) {
  width: 100%;
  margin-top: 10px;
  flex-direction: column;
  align-items: flex-start;
  font-weight: bold;
  .el-form-item__content {
    width: 100% !important;
  }
}

.Basic_information {
  width: 100%;
  :deep(.is-active) {
    font-weight: bold;
  }
  .el_information {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    :deep(.el-form-item) {
      width: 16%;
      height: auto;
      display: flex;
      align-items: flex-start;
      flex-direction: column;
      flex: none;
      margin-right: 4px;
      margin-bottom: 0;
      .el-form-item__label {
        margin-left: 0;
      }
      .el-form-item__content {
        width: 100% !important;
      }
    }
    .el_information_row {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
    }
  }
  .el-select {
    width: 100;
  }
}
:deep(.el_Processingresults) {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  .el_Processingresults_box {
    display: flex;
    flex-direction: column;
    width: 100%;
    .el_title {
      display: flex;
      width: fit-content;
      padding: 0 10px;
      margin-bottom: 4px;
      // border-left: 3px solid #172e60;
      position: relative;
    }
    .el_title::after {
      position: absolute;
      content: '';
      width: 6px;
      height: 6px;
      border-radius: 50%;
      left: 0;
      top: 50%;
      transform: translate(0, -50%);
      background-color: #172e60;
    }
    .el_Processingresults_box_list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-right: 11px;
      .el-form-item {
        width: 24%;
        height: auto;
        display: flex;
        flex-direction: row;
        .el-form-item__content {
          width: 100% !important;
        }
        .el-input-number {
          width: 100% !important;
        }

        .el-form-item__label {
          margin-bottom: 0;
        }
      }
    }
  }
}
:deep(.Responsible_box) {
  width: 100%;
  margin-top: 10px;
  .is-active {
    font-weight: bold;
  }
}
.el-endtabs {
  margin-top: 10px;
  :deep(.is-active) {
    font-weight: bold;
  }
}
:deep(.el-loading-mask) {
  position: fixed;
  left: 12%;
  top: 10%;
}
</style>
