<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{
          $route.query.index == '0' ? '回复' : $route.query.index == '1' ? '新增记录' : '完结'
        }}</span>
        <!-- <el-button class="button" v-if="$route.query.index=='1' || $route.query.index=='2'" @click="submit">提交</el-button> -->
      </div>
    </template>

    <div class="contemtMax">
      <div class="left">
        <el-form :model="endFrom" label-width="120px">
          <el-form-item label="运单商场" class="el_lab">
            <el-input v-model="endFrom.waybillMall" disabled placeholder="请输入运单商场" />
          </el-form-item>

          <!-- <el-form-item label="运单号">
            <el-input v-model="endFrom.waybillNumber" placeholder="请输入运单号" />
          </el-form-item> -->

          <!-- <el-form-item label="订单自编号">
            <el-input v-model="endFrom.orderCode" placeholder="请输入订单自自编号" />
          </el-form-item> -->

          <!-- <el-form-item label="包条码">
            <el-input v-model="endFrom.orderPackageCode" placeholder="请输入包条码" />
          </el-form-item> -->

          <!-- <div class="selector"> -->
          <div class="el-form-item el_lab">
            <span class="el-form-item__label">运损节点</span>
            <el-select
              v-model="endFrom.discoveryNode"
              filterable
              default-first-option
              :reserve-keyword="false"
              placeholder="运损发现节点"
              @change="TransportChange"
              disabled
            >
              <el-option
                v-for="item in TransportlossList"
                :key="item.value"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </div>
          <!-- </div> -->

          <!-- <el-form-item label="品类">
            <el-input v-model="endFrom.name" placeholder="请输入品类" />
          </el-form-item> -->

          <el-form-item label="异常类型" class="el_lab">
            <el-input v-model="endFrom.workOrderType" disabled placeholder="异常类型" />
            <!-- workOrderStatus -->
          </el-form-item>

          <el-form-item label="车次号" class="el_lab">
            <el-input v-model="endFrom.trainNumber" disabled placeholder="请输入车次号" />
          </el-form-item>

          <el-form-item label="运损时间" class="el_lab">
            <el-date-picker
              v-model="endFrom.warehousingTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择运损发现时间"
              disabled
            />
          </el-form-item>

          <el-form-item label="发货时间" class="el_lab">
            <el-date-picker
              v-model="endFrom.warehousingTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择发货时间"
              disabled
            />
          </el-form-item>
          <el-form-item label="钉钉流程号" class="el_lab">
            <el-input v-model="endFrom.processNumber" disabled placeholder="请输入钉钉流程号" />
          </el-form-item>

          <el-form-item label="处理方" class="el_lab">
            <el-select
              v-model="endFrom.processor"
              multiple
              filterable
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择处理方"
              disabled
              @change="ProcessingParty"
            >
              <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="" class="el_lab"> </el-form-item>
          <div class="el_dcl">
            <!-- <div class="selector">
              <div class="el-form-item">
                <span class="el-form-item__label">处理方</span>
                <el-select
                  v-model="endFrom.processor"
                  multiple
                  filterable
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择处理方"
                  @change="css"
                >
                  <el-option
                    v-for="item in warehouseData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div> -->

            <!-- <div class="el_Transport">
            <el-form-item label="运损发现节点">
              <el-radio-group v-model="endFrom.transportloss" @change="TransportChange">
                <el-radio v-for="item in TransportlossList" :label="item.label">{{
                  item.txt
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div> -->
          </div>
          <!-- <div class="selector">
            <div class="el-form-item selector">
              <span class="el-form-item__label">责任方</span>
              <el-select
                v-model="endFrom.duty"
                multiple
                filterable
                default-first-option
                :reserve-keyword="false"
                placeholder="请选择责任方"
              >
                <el-option
                  v-for="item in warehouseData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div> -->

          <el-tabs type="border-card" class="PackageInformation">
            <el-tab-pane label="包件信息">
              <div class="ResponsibilityBoxS">
                <div>
                  <!-- <el-button type="primary" @click="AddPackage"   disabled> 添加信息 </el-button> -->
                </div>
                <div class="el_btbox" v-for="(item, index) in PackageInfo" :key="index">
                  <div class="leftbox">
                    <div class="maxBox">
                      <span class="title">包条码:</span>
                      <el-input
                        disabled
                        v-model="item.packageCode"
                        placeholder="请输入包条码"
                        clearable
                        :rows="2"
                        @change="ChangePackageInfo(item.packageCode, index)"
                      />
                    </div>

                    <div class="maxBox">
                      <span class="title">订单自编码:</span>
                      <el-input
                        v-model="item.orderCode"
                        placeholder="请输入订单自编号"
                        clearable
                        disabled
                      />
                    </div>

                    <div class="maxBox">
                      <span class="title">运单号:</span>
                      <el-input
                        v-model="item.waybillNumber"
                        placeholder="请输入运单号"
                        clearable
                        disabled
                      />
                    </div>
                  </div>

                  <div class="el-btn">
                    <el-button v-if="item.state" type="primary" @click="historicalPackages(index)">
                      查看历史包件
                    </el-button>
                    <!-- <el-button type="primary" @click="PackagRemoval(index)" disabled>
                      移除
                    </el-button> -->
                  </div>
                </div>
                <div class="NumTotal">
                  <span>总件数:{{ PackageInfo.length }}</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>

          <el-tabs type="border-card" style="width: 100%">
            <el-tab-pane label="责任方信息">
              <div class="ResponsibilityBox">
                <div>
                  <!-- <el-button type="primary" @click="responsibleParty" disabled>
                    添加信息
                  </el-button> -->
                </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.description"
                        placeholder="请输入说明 "
                        clearable
                        :rows="2"
                        disabled
                      />
                    </div>
                  </div>
                  <div class="el-btn">
                    <!-- <el-button type="primary" disabled @click="ResponsibilityRemoval(index)">
                      移除
                    </el-button> -->
                  </div>
                </div>
                <div class="Proportion">
                  <span class="title">公司占比:{{ companyProportion }}</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <!-- 完善信息 -->
          <div class="Improveinformation">
            <el-tabs type="border-card" class="demo-tabs" 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 class="el_pklab">
                    <span class="title" :style="{ color: item.state != 0 ? '#000' : '#F56C6C' }"
                      >{{ item.state == 0 ? '赔款方' : '收款方' }}{{ item.cld }}</span
                    >
                  </div>

                  <div class="el_pkLi">
                    <div class="sk_input">
                      <el-input
                        v-model="item.name"
                        :placeholder="item.state == 0 ? '请填写赔款方' : '请填写收款方'"
                      />
                    </div>
                    <div class="sk_input">
                      <el-input v-model="item.reason" placeholder="请填写原因" />
                    </div>
                    <div class="sk_input">
                      <el-input
                        @input="amountMoney"
                        :min="0"
                        v-model="item.num"
                        placeholder="金额"
                      />
                    </div>

                    <div class="sk_input" v-if="item.state == 0">
                      <el-input v-model="item.explains" placeholder="请填写说明" />
                    </div>
                    <div class="sk_input" v-if="item.state == 1">
                      <!-- <el-input v-model="item.explain" placeholder="请填写说明" /> -->
                    </div>
                    <div class="el_cwBtn">
                      <el-button type="primary" v-if="item.state == 0"> 财务处理 </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="selector">
              <div class="el-form-item selector">
                <span class="el-form-item__label">处理结果</span>
                <el-select
                  v-model="endFrom.result"
                  multiple
                  filterable
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择处理结果"
                  @change="changeProcessingResults"
                  :disabled="$route.query.index == '0' || $route.query.index == '2'"
                >
                  <el-option
                    v-for="item in ProcessingResults"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  />
                </el-select>
              </div>
            </div>

            <div class="ProcessingResults" v-if="ProcessingList.length">
              <div class="title">处理结果-理赔金额</div>
              <div class="Listadmiration">
                <div class="name" v-for="(item, index) in ProcessingList" :key="index">
                  <span>{{ item.name }}:</span>
                  <el-input-number
                    v-model="item.input"
                    :min="item.min"
                    :max="item.max"
                    @change="TotalChange"
                    :disabled="$route.query.index == '0' || $route.query.index == '2'"
                  />
                  <div class="Paymentname" @click="PaymentSelection(item)">
                    {{ item.payment ? item.text : '支付方式' }}
                  </div>
                </div>
              </div>

              <div class="el_tool">
                <span>总金额:{{ TotalClaimAmount }}</span>
              </div>
              <!-- <div class="ZFlptime">
                 <span class="name">支付方式（此处单选）</span> 
                 <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> 
                支付方式多选 
                 <el-checkbox-group v-model="endFrom.compensationMethod">
         
            <el-checkbox
              :label="item.dictValue"
              border
              v-for="item in Paymentmethod"
              :key="item.dictKey"
            />
          </el-checkbox-group> 
              </div> -->

              <el-divider>
                <span class="ZFname">理赔支付时间</span>
              </el-divider>
              <div class="lptime">
                <!-- <span class="name">理赔支付时间</span> -->
                <el-date-picker
                  v-model="endFrom.compensationTime"
                  type="datetime"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled="$route.query.index == '0' || $route.query.index == '2'"
                  placeholder="请选择运理赔支付时间"
                />
              </div>
            </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.index == '0' || $route.query.index == '2'"
              />
            </el-form-item>

            <!-- 备注信息 -->
            <div class="notes">
              <el-form-item label="异常问题描述">
                <el-input
                  v-model="endFrom.problemDescription"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 4 }"
                  placeholder="请输入异常问题描述"
                  :disabled="$route.query.index == '0'"
                />
              </el-form-item>
            </div>

            <!-- 图片  -->
            <div class="Transport_damage_photos">
              <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="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </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.index == '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 class="ProcessingRecords" 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-row>
                    <!-- 列表模块 -->
                    <tablecmt
                      :columnList="recordList"
                      :tableData="recorddata"
                      :loading="loadingObj.list"
                      @inputTxt="recordinputsc"
                      @timeCheck="recordtimesc"
                      @btnCheck="recordbtnsc"
                      @selectCheck="recordselectsc"
                      @selection="recordselectionChange"
                    >
                    </tablecmt>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>

          <!-- 仲裁原因 -->
          <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="el_sub" v-if="$route.query.index != '0'">
            <el-button type="primary" class="button" @click="submit">提交</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="ovhe" :style="{ height: msgHight + 'px' }" ref="scrollContainer">
                  <el-timeline>
                    <el-timeline-item
                      placement="top"
                      v-for="(item, index) in MessageContent"
                      :key="index"
                    >
                      <!-- {time: '2021-08-06 16:00:00',content:'内容4',name:'营业部名称'}, -->
                      <el-card>
                        <div class="e_ico">
                          <el-icon><User /></el-icon>:
                          <h4>{{ item.username }}【{{ item.name }}】</h4>
                        </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="e_ico">
                          <el-icon><Timer /></el-icon>:
                          <p>{{ item.time }}</p>
                        </div>

                        <div class="tag" v-if="msgState == 1 || msgState == 2 || msgState == 3">
                          <el-tag class="mx-1" effect="dark"
                            >{{
                              msgState == 1
                                ? ' 待回复'
                                : msgState == 2
                                ? '已回复'
                                : msgState == 3
                                ? '已超时'
                                : ''
                            }}
                          </el-tag>
                        </div>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <!-- 输入框  -->
              </el-tab-pane>
              <div class="inputMax" v-loading="Msgloading" element-loading-text="Loading...">
                <div class="inputfell">
                  <div class="inputbtn">
                    <el-upload
                      ref="uploadRef"
                      class="upload-demo"
                      :action="doubledCount"
                      :headers="headers"
                      :on-success="fellSuccess"
                    >
                      <template #trigger>
                        <el-button type="primary">上传附件</el-button>
                        <div class="felltis" v-if="KFfeel.length">上传成功</div>
                      </template>
                    </el-upload>

                    <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"
                      />
                    </el-select>
                  </div>

                  <el-input
                    v-model="Msgtextarea"
                    :rows="4"
                    type="textarea"
                    placeholder="回复内容"
                  />
                </div>
                <div class="msgHf">
                  <el-button type="primary" @click="replyMessage()"> 回复 </el-button>
                </div>
              </div>
            </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-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,
} 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, isNumer } from '@/utils/util';
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(0); //聊天框吸顶距离
const scrollContainer = ref(null); //客服实例
const KFfeel = ref([]); //附件链接
const MessageResponsibility = ref([]); //消息的处理方选择
const Msgtextarea = ref(''); //回复框消息
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 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 warehouseData = ref([]); //处理方
const MessageContent = ref([]);
const CompensationParty = ref([
  { name: '', state: 0, num: null, reason: '', cld: 1, explains: '' }, //赔款方
  { name: '', state: 1, num: null, reason: '', cld: 1, explains: '' }, //收款方
]); //收/赔
const ProcessingList = ref([]); //处理结果已经选择的列表
// 责任方列表
const FangAddList = ref([
  { businessName: '', personResponsibleName: '', responsibilityRatio: '', description: '' },
]);
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,

  /** 列表数据 */
  data: [],
  // 处理记录
  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, '运损触发事件');
};

// 页面初始化数据
const onLoad = () => {
  
  // 获取角色权限
  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, '当前角色权限');
  });

  // 获取页面参数
  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;
      endFrom.value.result = [];
      endFrom.value.processor = [];
      endFrom.value.packageImage = [];
      //图片处理回显
      res.data.data.decreaseImageVOList.forEach(res => {
        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.typesOf == '1')
        .map(res => {
          return {
            businessName: res.businessId,
          };
        });

      FangAddList.value = res.data.data.personResponsibleVOS.map(res => {
        return {
          businessName: res.businessId, //责任人ID
          personResponsibleName: res.personResponsibleName, //责任人名称
          responsibilityRatio: res.responsibilityRatio, //占比
          description: res.description, //说明
        };
      });

      res.data.data.processorVOList.forEach(item => {
        if (item.typesOf == 2) {
          // 处理方
          endFrom.value.processor.push(item.businessId);
        }
      });
      console.log(endFrom.value.processor, ' endFrom.value.processor');
      getDictionaryBiz('pc_work_order').then(res => {
        //处理结果字典
        console.log(res, '环节字典');
        endFrom.value.workOrderType = res.data.data.find(
          res => res.dictKey == endFrom.value.workOrderType
        ).dictValue; //异常类型回显
      });

      //发现环节回显
      getDictionaryBiz('pc_discovery_node').then(res => {
        console.log(res, '发现环节');
        // ProcessingResults.value = res.data.data;
        TransportlossList.value = res.data.data;
        console.log(TransportlossList.value, '处理好的发现环节');
        // endFrom.discoveryNode
      });
      getDictionaryBiz('result_handling').then(res => {
        console.log(res, '发现环节');
        ProcessingResults.value = res.data.data;
      });

      // 公司占比回显计算
      let sum = 0;
      FangAddList.value.forEach(item => {
        sum = Number(item.responsibilityRatio) + sum;
      });
      companyProportion.value = 100 - sum;
      ProcessingList.value = res.data.data.processingResultsVO.processingMoneyEntityList.map(
        item => {
          endFrom.value.result.push(item.resultType);
          return {
            input: item.money,
            min: 0,
            max: 9999999999999999999999999999,
            state: item.resultType,
            payment: item.compensationMethod,
            name: item.resultTypeName,
            text: item.compensationMethodName,
          };
        }
      );

      // 总金额回显
      TotalClaimAmount.value = res.data.data.processingResultsVO.money;
      // 理赔支付时间
      endFrom.value.compensationTime = res.data.data.processingResultsVO.compensationTime;
      // 处理结果说明回显
      endFrom.value.resultDescription = res.data.data.processingResultsVO.resultDescription;

      // 完结信息回显
      // 收款方
      CompensationParty.value = [];
      if (res.data.data.completionRecipientEntityList.length > 0) {
        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, //收款方原因
            explains: item.explains, //收款方说明
            cld: index + 1,
          });
        });
      }
      // 赔款方
      if (res.data.data.completionRecordEntities.length > 0) {
        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, //收款方原因
            explains: item.explains, //收款方说明
            cld: index + 1,
          });
        });
      }
      endFrom.value.arbitrate= res.data.data.reasonArbitration; //仲裁原因
    
    });

  // 查询处理记录
  $_getTrackRecord({
  id:$route.query.id
  }).then(res=>{
  console.log(res,'处理记录返回值');
  details.recorddata=res.data.data.surveyRecordEntities
  })
  }

  // 异常类型业务字典
  getDictionaryBiz('work_order_status').then(res => {
    //处理结果字典
    endFrom.value.workOrderStatus = res.data.data.filter(
      obj => obj.dictKey == endFrom.value.workOrderStatus
    ).dictValue; //异常类型处理
  });

  // 支付方式字典
  getDictionaryBiz('payment_method').then(res => {
    //处理结果字典
    console.log(res);
    Paymentmethod.value = res.data.data;
  });

  getDeptWarehouse({}).then(res => {
    console.log(res, '处理方');
    res.data.data.forEach(item => {
      warehouseData.value.push({
        value: item.id,
        label: item.name,
      });
    });
  });
  Chathistory(); //聊天的历史记录
};

// 多开页面的时候刷新参数
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 = () => {
  // 聊天记录获取
  Msgloading.value = true; //开启加载效果
  MessageResponsibility.value = []; //清空选择内容
  Msgtextarea.value = ''; //清空输入框消息
  $_getSurveyRecord({
    id: $route.query.id,
  }).then(res => {
    let filetype = ''; //文件类型
    MessageContent.value = []; //先清空内容，防止内容重复叠加
    Msgloading.value = false; //关闭加载效果
    console.log(res, '聊天记录');
    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()
      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 : ''],
      });
    });
    // 滚动到最后
    setTimeout(() => {
      const container = scrollContainer.value;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }, 0);
  });
};

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 = val => {
  // 首先删除取消的项目
  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: '' };
    // 根据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 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 => {
  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++;
    }
  });
  CompensationParty.value.push({ name: '', state: 0, num: 0, reason: '', cld: som, explains: '' });
};
// 添加收款方
const AddPayee = () => {
  let som = 1;
  CompensationParty.value.forEach(item => {
    if (item.state == 1) {
      som++;
    }
  });
  CompensationParty.value.push({ name: '', state: 1, num: 0, reason: '', cld: som, explains: '' });
};
// 理赔总金额计算
const TotalChange = () => {
  TotalClaimAmount.value = 0;
  ProcessingList.value.forEach(item => {
    console.log(item);
    TotalClaimAmount.value += item.input;
  });
};
// 移除按钮
const payremove = (state, val) => {
  // 判断赔付方，至少保留一条数据
  let som = 0;
  if (state == 0) {
    CompensationParty.value.forEach(item => {
      if (item.state == 0) {
        som++;
      }
    });
    if (som == 1) {
      ElMessage({
        message: '赔款必填最少一条',
        type: 'warning',
      });
      return;
    }
  }
  CompensationParty.value.splice(val, 1);
  console.log('CompensationParty :>> ', CompensationParty);
  amountMoney();
};
// 公司占比计算
const ProportionInput = () => {
  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 amountMoney = () => {
  // 计算赔款金额总数
  TotalamountCompensation.value = 0;
  TotalamountReceived.value = 0;
  CompensationParty.value.forEach(item => {
    const _num = isNumer(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;
    }
  });
  console.log('赔款总计金额', TotalamountCompensation.value);
  console.log('收款总计金额', TotalamountReceived.value);
};

// 添加包件
const AddPackage = () => {
  PackageInfo.value.push({ packageCode: '', orderCode: '', waybillNumber: '' });
};
// 包件移除
const PackagRemoval = val => {
  PackageInfo.value.splice(val, 1); //移除当前点击的按钮
};
// 查看历史包件
const historicalPackages = val => {
  dialogHistoricalPackage.value = true; //打开历史包件弹窗
  HistorIndex.value = val;
  console.log(val);
};
// 查询包件信息自动回显
const ChangePackageInfo = (val, index) => {
  let data = {
    packageCode: val,
  };
  $_getAbnormalPackage(data).then(res => {
    console.log(res, '包件信息');
    console.log(res.data.data, '包件信息');

    const packageData = res.data.data[0];
    PackageInfo.value[index].orderCode = packageData.orderCode; //订单自编码
    PackageInfo.value[index].waybillNumber = packageData.waybillNumber; //运单号
    PackageInfo.value[index].orderId = packageData.orderId; //运单号
    PackageInfo.value[index].state = false; //状态

    if (res.data.data.length > 1) {
      HistoricalPackageList.value = res.data.data;
      PackageInfo.value[index].state = true; //状态
    }
    // packageCode; //包件码
    // //订单自编码
    // orderCode: orderId; //运单号
    // workOrderId; //工单id
    // workOrderNumber; //工单名称
    console.log(PackageInfo.value, '处理好的参数');
  });
};
// 新视频预览
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 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.index == '0' || $route.query.index == '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 submit = () => {
  console.log(UserPermissions.value, '当前角色');
  // if (UserPermissions.value == '职能客服' || UserPermissions.value == '客服经理' ) {

  // 完结的逻辑
  // 异常问题描述非必填
  if (routerState.value == 'end') {
    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;
    }
    if (!endFrom.value.arbitrate) {
      ElMessage({
        message: '请填写仲裁原因',
        type: 'warning',
      });
      return;
    }
    console.log(CompensationParty.value, 'CompensationParty');
    let info = JSON.parse(JSON.stringify(endFrom.value)); //拷贝要提交的数据
    console.log(info, 'info');
    let data = [
      {
        completionRecipientEntities: [], //收款方
        completionRecordEntities: [], //赔款方
        reasonArbitration: endFrom.value.arbitrate, //仲裁原因
        ...info,
      },
    ];
    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: item.reason, //说明
          workOrderId: info.id, //异常工单
          warehouseId: info.warehouseId, //仓库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(','),
          workOrderNumber: info.workOrderNumber, //工单号
          workOrderId: info.id, //异常工单
          warehouseId: info.warehouseId, //仓库ID
        });
      }
    });

    // 赔款方

    console.log(data, '处理好的值');
    // $_addCompletionEnd(data).then(res => {
    //   $router.push('/aftersales/aftersalesWorkOrder');
    //   console.log(res, '完结成功返回值');
    //   if (res.data.code == 200) {
    //     ElMessage({
    //       showClose: true,
    //       message: res.data.msg,
    //       type: 'success',
    //     });
    //   }
    // });
    // }else{
    //   ElMessage({
    //     message: '权限不足',
    //     type: 'warning',
    //   });
    //   console.log(UserPermissions.value);
    //   return;
    // }
  } else {
    if (UserPermissions.value != '仓库客服') {
      ElMessage({
        message: '权限不足',
        type: 'warning',
      });
      console.log(UserPermissions.value);
      return;
    }
    // 新增记录处理结果
    console.log($route.query.id, '异常ID');
    console.log(ProcessingList.value, 'ProcessingList12312');
    let info = JSON.parse(JSON.stringify(endFrom.value)); //拷贝要提交的数据
    let data = {
      aftersalesProcessingResultsDTO: {
        ...info,
      },
      processingMoneyEntityList: [], //赔付方式
    };
    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['compensationMethod'] = Paymentmethod.value.filter(
    //   item => item.dictKey == endFrom.value.compensationMethod
    // )[0].dictValue; //目前是单选

    // data['compensationMethod'] = endFrom.value.compensationMethod.join(','); //赔付方式多选
    // console.log(data['compensationMethod']);
    console.log(Paymentmethod.value, 'Paymentmethod.value');
    data.aftersalesProcessingResultsDTO['compensationMethod'] = ProcessingList.value
      .map(item => item.text)
      .join(',');
    data['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, //处理结果名字
          };
        } else {
          return null;
        }
      })
      .filter(item => item !== null);
    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;
    }

    console.log(data, '处理好的数据');
    delete data.aftersalesProcessingResultsDTO.id; //删除ID字段

    (data.aftersalesProcessingResultsDTO.warehouseId = info.warehouseId), //仓库ID
      console.log(data, '处理好的数据');
    $_addProcessingResults(data).then(res => {
      console.log(res, '提交后的参数');
      $router.push('/aftersales/aftersalesWorkOrder');
      if (res.code == 200) {
        ElMessage({
          showClose: true,
          message: res.data.msg,
          type: 'success',
        });
      }
    });
  }
};

// 消息回复
const replyMessage = () => {
  console.log(MessageContent.value, '当前的聊天记录');

  console.log(warehouseData.value, '参数1212312312312312');
  console.log(MessageResponsibility, '责任方');
  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',
      });
    }
  });
};

// 历史包件里面的查看
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; //打开历史包件弹窗
};
</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) {
    height: 50px;
    display: flex;
    align-items: center;
    margin: 0;
    margin-bottom: 10px;
    flex: 1 0 30%;
    .el-select {
      width: 100%;
    }
  }
  :deep(.el-form-item__label) {
    width: 100px !important;
    justify-content: flex-start;
  }
  :deep(.el-input--prefix) {
    width: 100%;
    height: 28.68px !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: 20px;
  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-right: 5%;
      margin-bottom: 20px;
      height: 30px;
      width: 45%;
      span {
        display: block;
        width: 30%;
        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-left: 26px;
  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: 20px;
  width: 100%;
  :deep(.custom-tabs-label) {
    display: flex;
    align-items: center;
  }
  .el_pklab {
    width: 50px;
  }

  .el_pkLi {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
.payanindemnity {
  display: flex;
  align-items: center;
  margin-top: 20px;
  .title {
    width: 126px;
    height: 100%;
    display: flex;
    display: block;
    align-items: center;
  }
  .sk_input {
    margin: 0 5px;
    margin-left: 20px;
    width: 20%;
  }
  .el-button {
    border: none;
  }
}
.arbitrate {
  width: 100%;
  margin-top: 20px;
  margin-left: 26px;
}
.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: 100px;
}
.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: 47%;
}
.contemtMax {
  display: flex;
  justify-content: space-between;

  .left {
    width: 68%;
    padding: 0 10px;
    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;
  }
  .leftbox {
    .title {
      width: 80px;
    }
  }
}
.el_dcl {
  display: flex;
  width: 100%;
}
.Proportion {
  font-size: 14px;
  color: #606266;
  margin-top: 30px;
}
.el_tool {
  span {
    font-size: 14px;
  }
}
.msgHf {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  :deep(.el-button) {
    margin-left: 20px;
  }
}
.ovhe {
  position: relative;
  overflow-y: scroll;
  scroll-behavior: smooth;
  .e_ico {
    display: flex;
    align-items: center;
  }
  .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;
    }
  }
}
.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;
      }
    }
  }
}
.el_cwBtn {
  width: 20%;
  display: flex;
  justify-content: flex-end;
}
.PackageInformation {
  width: 100%;
  margin-bottom: 10px;
}
.ResponsibilityBoxS {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  .leftbox {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .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;
  }
}
.el_sub {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin: 4px 0;
}
.el_resj {
  margin-top: 20px !important;
}
.el_lab {
  margin-right: 10px !important;
}
</style>
