<template>
  <div v-loading="Addloading" class="page_loading" element-loading-text="Loading...">
    <el-card class="box-card">
      <el-tabs type="border-card" class="topClass" @tab-change="TopChange">
        <el-tab-pane label="订单填写"></el-tab-pane>
        <el-tab-pane label="零担填写"></el-tab-pane>
      </el-tabs>

      <el-form
        :model="Indexform"
        label-width="100px"
        class="IndexFrom"
        ref="IndexForm"
        :rules="rules"
      >
        <el-form-item label="异常类型" prop="workOrderType" class="el_inputTop el_Exception">
          <el-select
            v-model="Indexform.workOrderType"
            clearable
            placeholder="选择工单异常类型"
            @change="abnormalChange"
          >
            <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="发现节点" prop="discoveryNode" class="el_inputTop">
          <el-select
            v-model="Indexform.discoveryNode"
            clearable
            placeholder="选择发现节点"
            @change="DiscoveringNodesChange"
          >
            <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-input
            v-model="Indexform.workOrderNumber"
            disabled
            placeholder="异常工单号(自动生成)"
            clearable
          />
        </el-form-item>

        <el-tabs type="border-card" class="PackageInformation">
          <el-tab-pane label="包件信息">
            <div class="ResponsibilityBoxS">
              <div
                class="el_packBtn"
                v-if="groundlineType == 3 || groundlineType == 5 || groundlineType == 6"
              >
                <el-button type="primary" @click="AddPackage"> 添加信息 </el-button>
              </div>
              <div class="el_btbox" v-for="(item, index) in PackageInfo" :key="index">
                <div class="leftbox">
                  <div class="maxBox" v-if="identifying != '2'">
                    <el-form-item label="包条码">
                      <el-tooltip
                        :content="item.packageCode ? item.packageCode : '包条码'"
                        placement="top"
                      >
                        <el-input
                          v-model="item.packageCode"
                          placeholder="请输入包条码"
                          clearable
                          @change="ChangePackageInfo(item.packageCode, index)"
                        />
                      </el-tooltip>
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="运单号">
                      <el-tooltip
                        :content="item.waybillNumber ? item.waybillNumber : '运单号'"
                        placement="top"
                      >
                        <el-input v-model="item.waybillNumber" placeholder="请输入运单号" />
                      </el-tooltip>
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="订单自编号">
                      <el-tooltip
                        :content="item.orderCode ? item.orderCode : '订单自编号'"
                        placement="top"
                      >
                        <el-input
                          v-model="item.orderCode"
                          :placeholder="identifying != '2' ? '订单自编号' : '请输入订单自编号'"
                        />
                      </el-tooltip>
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="一级品">
                      <el-input
                        v-model="item.first"
                        style="width: 240px"
                        placeholder="请输入一级品"
                      />
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="二级品">
                      <el-input
                        v-model="item.secondary"
                        style="width: 240px"
                        placeholder="请输入二级品"
                      />
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="品牌">
                      <el-tooltip
                        :content="item.brandName ? item.brandName : '品牌'"
                        placement="top"
                      >
                        <el-input
                          v-model="item.brandName"
                          :disabled="identifying != '2'"
                          :placeholder="identifying != '2' ? '品牌(自动带出)' : '请输入品牌'"
                        />
                      </el-tooltip>
                    </el-form-item>
                  </div>

                  <div class="maxBox" v-if="identifying != '1'">
                    <el-form-item> </el-form-item>
                  </div>
                </div>

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

        <!-- 必填(提货环节可以不填写运单号) -->
        <!-- 必填 -->

        <el-form-item
          label="车次号"
          prop="trainNumber"
          v-if="
            groundlineType == 3 || groundlineType == 5 || groundlineType == 7 || groundlineType == 6
          "
        >
          <!-- <el-input
          v-model="Indexform.trainNumber"
          placeholder="请输入车次号"
          clearable
    
        /> -->

          <el-select
            v-model="Indexform.trainNumber"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请选择车次号"
            @change="DeliveryTrainnumber"
          >
            <el-option
              v-for="item in TrainnumberList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="配送时间"
          prop="deliveryTime"
          v-if="groundlineType == 5 || groundlineType == 7 || groundlineType == 6"
        >
          <el-date-picker
            v-model="Indexform.deliveryTime"
            type="datetime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择配送时间"
          />
        </el-form-item>

        <!-- 必填 -->

        <el-form-item
          label="配送司机"
          prop="deliveryDriver"
          v-if="groundlineType == 5 || groundlineType == 7 || groundlineType == 6"
        >
          <el-input v-model="Indexform.deliveryDriver" placeholder="请输入配送司机" clearable />
          <!-- <el-select
          v-model="Indexform.deliveryDriver"
          filterable
          default-first-option
          :reserve-keyword="false"
          placeholder="请输入配送司机"
          @change="changeDeliveryDriver"
        >
          <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 prop="vehicleRoute" label="车辆路线" v-if="groundlineType == 3">
          <el-input v-model="Indexform.vehicleRoute" placeholder="请输入车辆路线" clearable />
        </el-form-item>

        <el-form-item label="发货时间" prop="deliverGoodsTime" v-if="groundlineType == 2">
          <el-date-picker
            v-model="Indexform.deliverGoodsTime"
            type="datetime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发货时间"
          />
        </el-form-item>

        <el-form-item label="入库时间" prop="warehousingTime" v-if="groundlineType == 4">
          <el-date-picker
            v-model="Indexform.warehousingTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择入库"
          />
        </el-form-item>

        <el-form-item
          label="发现时间"
          prop="discoveryTime"
          v-if="
            groundlineType == 4 || groundlineType == 5 || groundlineType == 6 || groundlineType == 7
          "
        >
          <el-date-picker
            v-model="Indexform.discoveryTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发现时间"
          />
        </el-form-item>

        <!-- <el-form-item label="一级品" prop="first">
        <el-input v-model="Indexform.first" placeholder="请输入一级品类" />
      </el-form-item> -->

        <!-- <el-form-item label="二级品" prop="secondary">
        <el-input v-model="Indexform.secondary" placeholder="请输入二级品类" />
      </el-form-item> -->

        <!-- 必填 -->
        <el-form-item label="运单商场" prop="waybillMall">
          <el-input v-model="Indexform.waybillMall" placeholder="请输入运单商场" />
        </el-form-item>

        <el-form-item label="合作模式">
          <el-input
            v-model="Indexform.typeServiceName"
            disabled
            placeholder="合作模式(存在则自动带出)"
            clearable
          />
        </el-form-item>

        <!-- <el-form-item label="钉钉流程号">
        <el-input v-model="Indexform.processNumber" placeholder="请输入钉钉流程号" />
      </el-form-item> -->

        <!-- 必填 -->
        <!-- <el-form-item label="异常问题描述">
        <el-input v-model="Indexform.problemDescription" placeholder="请输入异常问题" clearable />
      </el-form-item> -->

        <el-form-item label="处理方" prop="processor">
          <el-select
            v-model="Indexform.processor"
            clearable
            filterable
            multiple
            placeholder="请选择处理方"
            @change="Processingrelease"
          >
            <el-option
              v-for="item in warehouseData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="isShowFormItem1"></el-form-item>
        <el-form-item v-if="isShowFormItem2"> </el-form-item>
        <el-form-item v-if="isShowFormItem3"> </el-form-item>
        <el-form-item v-if="isShowFormItem4"> </el-form-item>

        <el-form-item label="调查经过" prop="investigationPocess" class="Investigationprocess">
          <el-input
            v-model="Indexform.investigationPocess"
            placeholder="请输入调查经过"
            clearable
            :rows="1"
            type="textarea"
          />
        </el-form-item>

        <el-tabs type="border-card" class="el_nint">
          <el-tab-pane label="内部责任划分">
            <div class="ResponsibilityBox">
              <div><el-button type="primary" @click="responsibleParty"> 添加信息 </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-form-item label="责任方" prop="processor">
                      <el-select
                        v-model="item.businessName"
                        clearable
                        placeholder="请选提货择责任方"
                        v-if="groundlineType == 1"
                      >
                        <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
                        clearable
                        placeholder="请选择责任方"
                        @change="ResponsiblePartychange(item.businessName, index)"
                      >
                        <el-option
                          v-for="item in warehouseData"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </div>

                  <div class="maxBox">
                    <el-form-item label="责任人">
                      <el-select
                        v-if="groundlineType != 1"
                        v-model="item.personResponsibleName"
                        clearable
                        filterable
                        placeholder="请选责任人"
                        allow-create
                        default-first-option
                      >
                        <el-option
                          v-for="item in item.personResponsibleList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>

                      <el-input
                        v-else
                        v-model="item.personResponsibleName"
                        placeholder="请输入责任人"
                      />
                    </el-form-item>
                  </div>
                  <div class="maxBox el_zb">
                    <el-form-item label="占比" class="title">
                      <el-input-number
                        :controls="false"
                        v-model="item.responsibilityRatio"
                        placeholder="占比 "
                        :min="0"
                        :max="item.ProportionMax"
                        :value-on-clear="0"
                        v-percentage
                        @input="CompanyProportionInput(item)"
                      />

                      <span class="percentage">%</span>
                    </el-form-item>
                  </div>
                  <div class="maxBox">
                    <el-form-item label="三方责任人">
                      <el-input v-model="item.tripartite" placeholder="请输入三方责任人" />
                    </el-form-item>
                  </div>

                  <div class="maxBox illustrate">
                    <el-form-item label="说明">
                      <el-input
                        v-model="item.description"
                        type="textarea"
                        placeholder="请输入说明 "
                        :rows="1"
                      />
                    </el-form-item>
                  </div>
                </div>
                <div class="el-btn el_btn_remove">
                  <el-button type="primary" @click="ResponsibilityRemoval(index)"> 移除 </el-button>
                </div>
              </div>
              <div class="Proportion">
                <span class="title">公司占比:{{ companyProportion }}%</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-tabs type="border-card" class="el_Processingresults" v-if="ProcessingreleaseState">
        <el-tab-pane label="处理结果">
          <div class="selector">
            <el-select
              v-model="Indexform.result"
              multiple
              filterable
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择处理结果"
              @change="changeProcessingResults"
            >
              <el-option
                v-for="item in ProcessingResults"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </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 style="width: 120px">{{ item.name }}:</span>
                <div class="payment_right">
                  <el-input-number
                    v-model="item.input"
                    :min="item.min"
                    :max="item.max"
                    @change="TotalChange"
                  />
                  <div class="Paymentname" @click="PaymentSelection(item)">
                    {{ item.payment ? item.text : '支付方式' }}
                  </div>
                  <div class="el_PaymentUnit">
                    <el-input v-model="item.paymentUnit" placeholder="请输入支付单位" />
                  </div>
                  <el-date-picker
                    v-model="item.compensationTime"
                    type="datetime"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="理赔支付时间"
                  />
                </div>
              </div>
            </div>

            <div class="el_tool">
              <span>总金额:{{ TotalClaimAmount }}</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="Transport_damage_photos" v-if="SelectType == 1 || SelectType == 3">
        <span class="title">{{
          SelectType == 1 ? '货损照片(2张)' : SelectType == 3 ? '窜货照片(1张)' : '照片'
        }}</span>
        <el-upload
          v-model:file-list="Indexform.packList"
          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="dialog-footer footer_el">
        <!-- <el-button @click="Indexdialog = false">取消</el-button> -->
        <el-button type="primary" @click="ConfirmForm"> 提交 </el-button>
      </div>
    </el-card>

    <!-- <div v-if="routerState" class="foot_btn">
    <el-button type="primary" @click="ConfirmForm">新增记录</el-button>
    <el-button type="primary" @click="ConfirmForm">完结 </el-button>
    <el-button type="primary" @click="ConfirmForm">打回 </el-button>
  </div> -->

    <!-- 少货件数大于3 -->
    <el-dialog
      :show-close="false"
      v-model="ShortageState"
      title="少货件数"
      width="40%"
      @close="ShortageStateFun"
      lock-scroll
      draggable
    >
      <div class="ShortageStatenum" v-for="item in ShortageList">
        <span class="title">件数{{ item.number }}</span
        ><el-input v-model="item.packageCode" placeholder="请输入包条码" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShortageCancellation">取消</el-button>
          <el-button type="primary" @click="ShortageState = false"> 确认信息 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 窜货件数大于3 -->
    <el-dialog
      :show-close="false"
      v-model="fleeingState"
      title="窜货件数"
      width="40%"
      @close="fleeingFun"
      lock-scroll
      draggable
    >
      <div class="ShortageStatenum" v-for="item in fleeingList">
        <span class="title">件数{{ item.number }}</span
        ><el-input v-model="item.packageCode" placeholder="请输入包条码" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fleeingCancellation">取消</el-button>
          <el-button type="primary" @click="ShortageState = false"> 确认信息 </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="ZFdialog" title="支付方式选择" width="45%" class="ZFfsLoad">
      <el-radio-group v-model="Indexform.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(Indexform.compensationMethod)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
const $store = useStore();
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { getDetailWarehouse, getDeptWarehouse } from '@/api/basicdata/basicdataWarehouse'; //处理方
import {
  $_getList,
  $_submit,
  $_getDetail,
  $_remove,
  $_getBusinessDepartmentUser,
  $_getAbnormalPackage,
  $_shippingInformation,
} from '@/api/aftersales/aftersalesWorkOrder';
import { compressImageBlob } from '@/components/IMGcompressor/imgcompressor.js';
import { computeNumber } from '@/utils/util';
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import { getToken } from '@/utils/auth';
const $router = useRouter();
const $route = useRoute();
const Indexform = ref({
  packList: [],
  decreaseImageEntityList: [], //处理好的图片数据
  discoveryNode: '1',
}); //首页新增表单
const ProcessingResults = ref([]); //处理结果列表选项
const Addloading = ref(false);
const IndexException = ref([]); //异常类型下拉选择
const ZFname = ref(''); //支付名字预留状态
const IndexForm = ref(null); //表格ref实力
const DiscoveringNodes = ref([]); //发现节点下拉选择
const warehouseData = ref([]); //处理方
const SelectType = ref(null); //类型
const HistoricalPackageinput = ref(''); //历史包件选择
const dialogImageUrl = ref(null); //图片
const dialogVisible = ref(null); //图片
const groundlineSet = ref(true); //干线条件都满足
const TotalClaimAmount = ref(0); //总金额
const TrainnumberList = ref([]); //车次号列表
const TrainnumberMax = ref([]); //所有车次号
const groundlineType = ref(null); //干线状态
const Inputbox = ref(true); //调查经过输入框状态
const ShortageState = ref(false); //少货件数弹窗状态
const fleeingState = ref(false); //窜货件数弹窗
const DeliveryprocessData = ref([]); //配送环节数据
const ShortageList = ref([]); //少货件数
const fleeingList = ref([]); //窜货件数
const valueStrictly = ref();
const ProcessingreleaseState = ref(false); //是否可以填写处理结果
const routerID = ref(null); //路由参数ID
const routerState = ref(''); //路由状态
const personResponsibleList = ref([]); //责任人列表
const ZFdialog = ref(false); //支付方式弹出
const companyProportion = ref(100); //公司占比
const identifying = ref(1); //订单，零担状态
const MainlineUnloadingData = ref([]); //干线卸货数据
const dialogHistoricalPackage = ref(false); //历史包件弹窗
const HistoricalPackageList = ref([]); //历史包件数组
const DeliveryprocessTime = ref([]); //配送环节时间
const HistorIndex = ref(0); //历史包件索引
const NumberPackages = ref(0); //包件个数
const dialogImgList = ref(false); //图片预览弹窗
const amplifyurl = ref(''); //当前点击的图片
const amplifysrcList = ref([]); //图片循环列表
const ProcessingList = ref([]); //处理结果已经选择的列表
const Paymentmethod = ref([]); //支付方式
const Mydata = ref(); //当前登录人信息
const PackageInfo = ref([
  //包件信息
  {
    packageCode: '',
    orderCode: '',
    first: '',
    secondary: '',
    waybillNumber: '',
    brandName: '',
    state: false,
  },
]);
// 责任方列表
const FangAddList = ref([
  {
    businessName: '',
    personResponsibleName: '',
    responsibilityRatio: '',
    description: '',
    tripartite: '',
    ProportionMax: 100,
  },
]);
// 提货责任方
const responsible = ref([
  {
    value: '1',
    label: '工厂',
  },
  {
    value: '2',
    label: '外包搬运',
  },
  {
    value: '3',
    label: '物流',
  },
]);

const DeliveryDriver = ref([]);
// 图片列表
const fileList = ref([]);
// 字典公共函数
function updateDictionary(targetArray, dictionaryType) {
  getDictionaryBiz(dictionaryType).then(res => {
    console.log(res, '字典');
    res.data.data.forEach(item => {
      targetArray.push({
        value: item.dictKey,
        label: item.dictValue,
      });
    });
  });
}
// 图片上传必须携带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(Indexform.value['packList'], '图片列表');
    amplifysrcList.value.push(response.data.link);
  }
};

// 上传图片规则
const beforeAvatarUpload = async rawFile => {
  console.log(rawFile);
  if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式只能为 png/jpg!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能大于10MB!');
    return false;
  }
  const res = await compressImageBlob(rawFile);
  return res;
};
// 点击图片列表回调
const pictureList = val => {
  console.log(val, '图片列表');
  dialogImgList.value = true;
  console.log(val, '图片列表');
  amplifyurl.value = val.url;
};
// 点击图片移除
const ImgListRemove = val => {
  console.log(val, '移除图片');
  amplifysrcList.value = amplifysrcList.value.filter(item => item !== val.response.data.link);
};
// 处理方和责任方获取数据
const handle = () => {
  getDeptWarehouse().then(res => {
    res.data.data.forEach(item => {
      warehouseData.value.push({
        value: item.id,
        label: item.name,
      });
    });
  });
};

// 获取当前责任方的责任人
const ResponsiblePartychange = (val, index) => {
  if (!val) {
    return;
  }
  FangAddList.value[index].personResponsibleName = null; //清空当前选择的责任人
  $_getBusinessDepartmentUser({
    warehouseId: val,
  }).then(res => {
    console.log(res, '获取责任人列表');
    FangAddList.value[index].personResponsibleList = res.data.data;
  });
};
const onLoad = () => {
  // DeliveryTrainnumber(); //获取司机
  console.log($route.query.id, '页面初始化');
  routerState.value = $route.query.routerState;
  if (localStorage.getItem('my_data')) {
    Mydata.value = JSON.parse(localStorage.getItem('my_data')); //获取本地仓库信息
    console.log(Mydata.value, '记录本地登录');
  }

  updateDictionary(IndexException.value, 'pc_work_order'); //异常类型
  updateDictionary(DiscoveringNodes.value, 'pc_discovery_node'); //发现环节
  handle(); //处理方和责任方信息
  getDictionaryBiz('result_handling').then(res => {
    console.log(res, '发现环节');
    ProcessingResults.value = res.data.data;
  });
  // 支付方式字典
  getDictionaryBiz('payment_method').then(res => {
    //处理结果字典
    console.log(res);
    Paymentmethod.value = res.data.data;
  });

  Indexform.value.discoveryNode = '1'; //默认发现节点
  groundlineType.value = Indexform.value.discoveryNode;
  Indexform.value.workOrderType = '1'; //默认一个异常类型
  SelectType.value = Indexform.value.workOrderType;
};
onLoad(); //初始化程序

// 处理结果
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: '',
      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 abnormalChange = val => {
  console.log(val, '异常事件类型');
  SelectType.value = false;
  if (val == 1 || val == 2 || val == 3) {
    SelectType.value = val;
  } else {
    SelectType.value = null;
  }
  // 运损无数据默认0
  // if (val == 1) {
  //   Indexform.value.packageCode = 0;
  // } else {
  //   Indexform.value.packageCode = null;
  // }
  // 切换类型重置图片
  Indexform.value['packList'] = [];
  console.log(Indexform.value);
};

// 发现节点事件
const DiscoveringNodesChange = val => {
  groundlineSet.value = false; //干线条件都不满足
  if (
    val == 1 ||
    val == 2 ||
    val == 3 ||
    val == 4 ||
    val == 5 ||
    val == 6 ||
    val == 8 ||
    val == 7
  ) {
    groundlineType.value = val; //干线状态
    console.log(val);
  } else {
    groundlineType.value = null; //干线状态
  }
};

// 车次号自动带出时间司机
function DeliveryTrainnumber() {
  if (groundlineType.value == 5 || groundlineType.value == 6) {
    let dataInfo = DeliveryprocessData.value.find(
      res => res.trainNumber == Indexform.value.trainNumber
    );
    if (dataInfo) {
      console.log(dataInfo, '车次号筛选出来的数据');
      Indexform.value.deliveryTime = dataInfo.taskTime; //配送时间
      Indexform.value.deliveryDriver = dataInfo.driverName; //配送人
    }
  }

  if (groundlineType.value == 3) {
    let dataMain = MainlineUnloadingData.value.find(
      res => res.trainNumber == Indexform.value.trainNumber
    );
    if (dataMain) {
      Indexform.value.vehicleRoute = dataMain.vehicleRoute; //配送路线
    }
  }

  return;
}
// 理赔总金额计算
const TotalChange = () => {
  TotalClaimAmount.value = 0;
  ProcessingList.value.forEach(item => {
    console.log(item);
    TotalClaimAmount.value += item.input;
  });
};
// 支付方式选择
const PaymentSelection = val => {
  console.log(val, '支付');
  console.log(Paymentmethod.value);
  if (val.payment) {
    //支付方式回显
    let data = Paymentmethod.value.find(item => item.dictKey == val.payment);
    Indexform.value.compensationMethod = data.dictKey;
  } else {
    Indexform.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 handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = uploadFile => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

// 添加包件
const AddPackage = () => {
  PackageInfo.value.push({
    packageCode: '',
    orderCode: '',
    waybillNumber: '',
    brandName: '',
    state: false,
    mallName: '',
    secondary: '',
    first: '',
  });
};
// 包件移除
const PackagRemoval = val => {
  PackageInfo.value.splice(val, 1); //移除当前点击的按钮
  Statistics();
};

// 责任方添加
const responsibleParty = () => {
  let sum = 0;
  FangAddList.value.forEach(item => {
    console.log(item.responsibilityRatio, '当前比例');
    sum += item.responsibilityRatio;
  });
  console.log(sum, '当前总和');
  let max = 100 - sum;
  console.log('添加了责任方');
  FangAddList.value.push({
    businessName: '',
    personResponsibleName: '',
    tripartite: '',
    responsibilityRatio: '',
    description: '',
    ProportionMax: max,
  });
  console.log(max, '当前最大值');
};
// 责任移除
const ResponsibilityRemoval = val => {
  FangAddList.value.splice(val, 1); //移除当前点击的按钮
  CompanyProportion(val);
};
// 顶部标签切换
const TopChange = val => {
  SelectType.value = null; //重置照片类型
  PackageInfo.value = [
    {
      packageCode: '',
      orderCode: '',
      waybillNumber: '',
      brandName: '',
      state: false,
      mallName: '',
      secondary: '',
      first: '',
    },
  ]; //重置包件信息
  Indexform.value = {}; //重置表单

  if (val == 0) {
    identifying.value = 1;
  } else {
    identifying.value = 2;
  }
  console.log(identifying.value, '当前菜单id');
  // 重置责任方列表
  FangAddList.value = [
    {
      businessName: '',
      personResponsibleName: '',
      responsibilityRatio: '',
      description: '',
      tripartite: '',
      ProportionMax: 100,
    },
  ];
  // 重置公司占比
  companyProportion.value = 100;
  Processingrelease();
};

// 公司占比计算
const CompanyProportion = val => {
  setTimeout(() => {
    console.log(FangAddList.value, ' FangAddList.value');
    let proportion = 0; //责任比例之和
    FangAddList.value.forEach(item => {
      proportion += Number(item.responsibilityRatio);
    });
    // companyProportion.value公司占比
    companyProportion.value = 100 - proportion;

    let sum = 0;
    FangAddList.value.forEach(item => {
      console.log(item.responsibilityRatio, '当前比例');
      sum += item.responsibilityRatio;
    });
    let max = 100 - sum + Number(val.responsibilityRatio);
    console.log('MAX当前最大值', max);
    if (val.ProportionMax) {
      val.ProportionMax = max;
    }
  }, 0);
};
// 公司占比事件
const CompanyProportionInput = item => {
  console.log(item, '接收的值');
  CompanyProportion(item);
};

// 表单校验规则
const rules = reactive({
  trainNumber: [{ required: true, message: '请填写车次号', trigger: 'blur' }],
  deliveryTime: [{ required: true, message: '请填写配送时间', trigger: 'blur' }],
  deliveryDriver: [{ required: true, message: '请填写配送司机', trigger: 'blur' }],
  vehicleRoute: [{ required: true, message: '请填写车辆线路', trigger: 'blur' }],
  deliverGoodsTime: [{ required: true, message: '请填写发货时间', trigger: 'blur' }],
  discoveryTime: [{ required: true, message: '请填写发现时间', trigger: 'blur' }],
  // first: [{ required: true, message: '请填写一级品', trigger: 'blur' }],
  // secondary: [{ required: true, message: '请填写二级品', trigger: 'blur' }],
  warehousingTime: [{ required: true, message: '请填写入库时间', trigger: 'blur' }],
  processor: [{ required: true, message: '请填选择处理方', trigger: 'blur' }],
  waybillMall: [{ required: true, message: '请填写运单商场', trigger: 'blur' }],
  workOrderType: [{ required: true, message: '请选择异常类型', trigger: 'blur' }],
  discoveryNode: [{ required: true, message: '请选择发现节点', trigger: 'blur' }],
  investigationPocess: [{ required: true, message: '请填写调查经过', trigger: 'blur' }],
});
function validateDataItem(item) {
  const fields = [
    { key: 'businessName', message: '责任方不能为空' },
    { key: 'personResponsibleName', message: '责任人不能为空' },
    { key: 'tripartite', message: '三方责任人不能为空' },
    { key: 'description', message: '说明不能为空', emptyCheck: true },
  ];

  for (const field of fields) {
    const value = item[field.key];
    const isInvalid = field.emptyCheck ? value === '' : !value;
    if (isInvalid) {
      ElMessage({
        message: field.message,
        type: 'warning',
      });
      return false;
    }
  }
  return true;
}

//表单提交
const ConfirmForm = () => {
  IndexForm.value.validate(valid => {
    if (valid) {
      // 表单验证通过，处理表单提交
      //  提货责任方
      // 支付方式校验
      if (ProcessingList.value.length) {
        for (let item of ProcessingList.value) {
          if (!item.payment) {
            ElMessage({
              message: `请选择${item.name}的支付方式`,
              type: 'warning',
            });
            return;
          }
        }
      }
      // 内部责任划分校验
      if (!FangAddList.value.length) {
        ElMessage({
          message: `请填写内部责任划分`,
          type: 'warning',
        });
        return;
      }
      for (const item of FangAddList.value) {
        if (!validateDataItem(item)) {
          return;
        }
      }

      // 判断干线，配送环节是否是同一个运单号和订单号
      if (['3', '5', '6'].includes(groundlineType.value)) {
        if (PackageInfo.value.length) {
          // 判断是否同一个运单号
          const allSameA = PackageInfo.value.every(
            (item, _, self) => item.waybillNumber === self[0].waybillNumber
          );

          if (!allSameA) {
            ElMessage({
              message: '请输入同一个运单号',
              type: 'warning',
            });
            return;
          }
          // 判断是否同一个订单自编号
          const allSameB = PackageInfo.value.every(
            (item, _, self) => item.orderCode === self[0].orderCode
          );
          if (!allSameB) {
            ElMessage({
              message: '请输入同一个订单自编号',
              type: 'warning',
            });
            return;
          }
        }
      }
      console.log(Indexform.value.businessMame, '提货责任方');

      let DataSubmit = {
        personResponsibleDTO: [],
        packageEntityList: [], ////包件信息
        decreaseImageEntityList: [], //图片信息
        processingMoneyEntityList: [], //赔付方式
        aftersalesProcessingResultsDTO: {}, //处理结果
        ...Indexform.value,
      }; //解构表单参数

      // 图片类型:10运损,20窜货
      // decreaseImageEntityList:[
      //   {imageType:10,imageName:'图片名称',imagePath:'图片路径'},
      //   {imageType:10,imageName:'图片名称',imagePath:'图片路径'},
      // ]
      console.log(Indexform.value['packList'], '图片列表');
      // 处理图片(当类型为货损或为窜货才执行下面的东西)
      if (SelectType.value == 1 || SelectType.value == 3) {
        if (Indexform.value['packList']) {
          Indexform.value['packList'].forEach(item => {
            DataSubmit['decreaseImageEntityList'].push({
              imageType: SelectType.value == 1 ? 10 : SelectType.value == 3 ? 20 : '',
              imageName: item.response.data ? item.response.data.originalName : '',
              imagePath: item.response.data ? item.response.data.link : '',
            });
          });
        }
      }

      if (SelectType.value == 1 && DataSubmit['decreaseImageEntityList'].length < 2) {
        ElMessage({
          message: '货损至少提供2张图片附件',
          type: 'warning',
        });
        return;
      }

      if (SelectType.value == 3 && !DataSubmit['decreaseImageEntityList'].length) {
        ElMessage({
          message: '窜货必须提供图片附件',
          type: 'warning',
        });
        return;
      }

      console.log(DataSubmit['decreaseImageEntityList'], '处理好的图片');
      //司机信息处理
      // if (Indexform.value.deliveryDriver) {
      //   console.log(DeliveryDriver.value, '当前全部司机');
      //   console.log(Indexform.value.deliveryDriver, '选择的司机信息');
      //   Indexform.value.deliveryDriver = DeliveryDriver.value.find(
      //     item => item.id == Indexform.value.deliveryDriver
      //   ).driverName;
      // }

      console.log(Indexform.value.deliveryDriver, '筛选出来的司机');

      let processorEntityList = [];

      DataSubmit.processorEntityList = processorEntityList;
      DataSubmit.decreaseImageEntityList = JSON.parse(
        JSON.stringify(Indexform.value['decreaseImageEntityList'])
      );
      console.log(Indexform.value.workOrderNumber, 'Indexform.workOrderNumber12312312');
      // 包件信息
      // packageEntityList
      // 如果存在包件信息进行处理
      if (PackageInfo.value.length) {
        PackageInfo.value.forEach(item => {
          if (item.packageCode) {
            DataSubmit['packageEntityList'].push({
              number: PackageInfo.value.length, //数量
              packageCode: item.packageCode ? item.packageCode : null, //包件码
              waybillNumber: item.waybillNumber ? item.waybillNumber : null, //运单号
              orderCode: item.orderCode ? item.orderCode : null, //订单自编码
              brandName: item.brandName ? item.brandName : null, //品牌
              first: item.first ? item.first : null, //一级品类
              secondary: item.secondary ? item.secondary : null, //二级品类
            });
          }
        });
        DataSubmit.packageCode = [...new Set(PackageInfo.value.map(item => item.packageCode))].join(
          ','
        ); //包条码
        DataSubmit.waybillNumber = [
          ...new Set(PackageInfo.value.map(item => item.waybillNumber)),
        ].join(','); //运单号
        DataSubmit.brandName = [...new Set(PackageInfo.value.map(item => item.brandName))].join(
          ','
        ); //品牌
        DataSubmit.orderCode = [...new Set(PackageInfo.value.map(item => item.orderCode))].join(
          ','
        ); //包件信息订单自编码
      }

      // DataSubmit['packageEntityList'].push({
      //   workOrderId: Indexform.workOrderNumber, //异常ID
      //   number: PackageInfo.value.length, //数量
      //   packageCode: PackageInfo.value.map(item => item.packageCode).join(','), //包件码
      //   warehouseId: '', //仓库ID
      //   packageImage: Indexform.value['packList'].map(item => item.url).join(','), //包件图片路径
      //   waybillNumber: PackageInfo.value.map(item => item.waybillNumber).join(','), //运单号
      //   orderCode: PackageInfo.value.map(item => item.orderCode).join(','), //订单自编码
      // });

      // 总件数
      Indexform.value.number = PackageInfo.value.length;
      console.log(DataSubmit['packageEntityList'], '包件信息');
      // 调查经过
      DataSubmit.surveyRecordDTO = {
        content: Indexform.value.investigationPocess,
        // workOrderId: Indexform.value.workOrderNumber ? Indexform.value.workOrderNumber : null,
      };
      console.log(DataSubmit.surveyRecordDTO, '调查经过');
      // 环节责任方填写校验
      // 对在库环节,配送环节,安装环节进行责任人填写校验
      if (groundlineType.value == 5 || groundlineType.value == 4 || groundlineType.value == 7) {
        const Humanverification = FangAddList.value.every(item => item.businessName !== '');
        if (!Humanverification) {
          ElMessage({
            message: '请填写责任人',
            type: 'warning',
          });
          return;
        }
      }
      // 新责任方处理
      // FangAddList.value
      // 不是提货环节

      if (groundlineType.value != 1) {
        if (FangAddList.value.length) {
          // 如果存在责任方
          FangAddList.value.forEach(item => {
            DataSubmit['personResponsibleDTO'].push({
              businessName:
                warehouseData.value.find(obj => obj.value == item.businessName)?.label || null, //责任方名称
              businessId:
                warehouseData.value.find(obj => obj.value == item.businessName)?.value || null,
              wordOrderId: Indexform.value.workOrderNumber, //异常工单ID
              description: item.description ? item.description : null, //说明
              personResponsibleId:
                item.personResponsibleList.find(obj => obj.id == item.personResponsibleName)?.id ||
                null, //责任人ID
              personResponsibleName:
                item.personResponsibleList.find(obj => obj.id == item.personResponsibleName)
                  ?.name || item.personResponsibleName, //责任人名称
              responsibilityRatio: item.responsibilityRatio ? item.responsibilityRatio : null, //责任比例
              tripartite: item.tripartite ? item.tripartite : null, //三方责任人
            });
          });
        }
      } else {
        // 提货环节责任人处理
        FangAddList.value.forEach(item => {
          DataSubmit['personResponsibleDTO'].push({
            businessName:
              responsible.value.find(obj => obj.value == item.businessName)?.label || null, //责任方名称
            businessId:
              responsible.value.find(obj => obj.value == item.businessName)?.value || null,
            wordOrderId: Indexform.value.workOrderNumber ? Indexform.value.workOrderNumber : null, //异常工单ID
            description: item.description ? item.description : null, //说明
            personResponsibleName: item.personResponsibleName ? item.personResponsibleName : null, //责任人名称
            responsibilityRatio: item.responsibilityRatio ? item.responsibilityRatio : null, //责任比例
            tripartite: item.tripartite ? item.tripartite : null, //三方责任人
          });
        });
      }

      //公司占比
      if (companyProportion.value) {
        DataSubmit.companyProportion = companyProportion.value;
      }
      console.log(DataSubmit['personResponsibleDTO'], '新责任方处理的数据');
      //console.log(Indexform.value.duty.length);
      //责任方信息处理
      //责任方信息处理
      if (Indexform.value.processor.length) {
        Indexform.value.processor.forEach(item => {
          let found = warehouseData.value.find(element => element.value == item.toString());
          processorEntityList.push({
            businessName: found ? found.label : '',
            businessId: item,
            conditions: 1,
            typesOf: 2,
          });
        });
      }

      if (FangAddList.value.length) {
        FangAddList.value.forEach(item => {
          console.log(item, 'item');
          processorEntityList.push({
            businessName:
              groundlineType.value != 1
                ? warehouseData.value.find(obj => obj.value == item.businessName)?.label || null
                : responsible.value.find(obj => obj.value == item.businessName)?.label || null,
            businessId: item.businessName,
            conditions: 1,
            typesOf: 1,
          });
        });
      }
      DataSubmit.identifying = identifying.value; //1订单2零担3库存品

      console.log(processorEntityList, '老责任方处理好的数据');

      // 处理结果填写

      if (ProcessingList.value.length) {
        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;
        }
        DataSubmit.aftersalesProcessingResultsDTO.money = sum; //金额汇总
        DataSubmit.aftersalesProcessingResultsDTO.processingMoneyEntityList = ProcessingList.value
          .map(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 : null, //支付方式ID
                compensationMethodName: paymentMethodMatch ? paymentMethodMatch.dictValue : null, //支付方式名字
                resultName: item.name, //处理结果名字
                compensationTime: item.compensationTime, //支付时间
                paymentUnit: item.paymentUnit, //支付单位
              };
            } else {
              return null;
            }
          })
          .filter(item => item !== null);

        DataSubmit.aftersalesProcessingResultsDTO['compensationMethod'] = ProcessingList.value
          .map(item => item.text)
          .join(','); //支付方式拼接

        DataSubmit.aftersalesProcessingResultsDTO['resultType'] = ProcessingList.value
          .map(item => item.name)
          .join(','); //处理结果说明文字拼接
      }

      delete DataSubmit.duty; //移除多余字段
      delete DataSubmit.packList; //移除图片原始字段
      delete DataSubmit.processor; //移除多余字段
      console.log(DataSubmit, '处理好的数据');
      // 提交表单信息stringify

      Addloading.value = true; //开启页面加载
      $_submit(DataSubmit)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage({
              message: res.data.msg,
              type: 'success',
            });
            Indexform.value = {}; //重置表单
            $store.commit('DEL_TAG_CURRENT'); //关闭当前页面
            $router.push('/aftersales/aftersalesWorkOrder'); //添加成功跳转到列表
          }
        })
        .catch(res => {
          console.log(res, '错误信息');
          ElMessage.error('提交失败,请刷新页面重新尝试');
        })
        .finally(() => {
          Addloading.value = false; //闭页面加载
        });
    } else {
      console.log('表单验证失败');
      ElMessage({
        message: '请填完整信息',
        type: 'warning',
      });
    }
  });
};
// 选择司机带出车次号日期
const changeDeliveryDriver = val => {
  console.log(val);
  console.log(DeliveryDriver.value, '司机信息');
  Indexform.value.trainNumber = DeliveryDriver.value.find(res => res.id == val).trainNumber; //车次号
  Indexform.value.deliveryTime = DeliveryDriver.value.find(res => res.id == val).taskTime; //日期
};
// 少货件数对应事件
const ShortageTtems = val => {
  ShortageList.value = []; //进入之前重置参数
  const pattern = /\s+/g;
  const result = val.replace(pattern, '');
  console.log(result); // 输出 "33"
  Indexform.value.number = result;
  if (Indexform.value.number > 1) {
    ShortageState.value = true; //数量大于1，开启弹窗输入
  }
  for (let i = 0; i < val; i++) {
    ShortageList.value.push({
      number: i + 1, //件数
      packageCode: null, //输入框
    });
  }
};
// 少货关闭回调
const ShortageStateFun = () => {
  ShortageList.value.forEach(item => {
    if (item.packageCode == null) {
      Indexform.value.number = null;
    }
  });
};
// 少货按钮取消
const ShortageCancellation = () => {
  Indexform.value.number = null; //少货件数
  ShortageList.value = []; //进入之前重置参数
  ShortageState.value = false; //关闭弹窗
};
// 窜货关闭回调
const fleeingFun = () => {
  fleeingList.value.forEach(item => {
    if (item.packageCode == null) {
      Indexform.value.number = null;
    }
  });
};
// 窜货取消事件
const fleeingCancellation = () => {
  Indexform.value.number = null; //少货件数
  fleeingList.value = []; //进入之前重置参数
  fleeingState.value = false; //关闭弹窗
};
// 窜货输入框
const fleeingTtems = val => {
  fleeingList.value = []; //进入之前重置参数
  const pattern = /\s+/g;
  const result = val.replace(pattern, '');
  console.log(result); // 输出 "33"
  Indexform.value.number = result;
  if (Indexform.value.number > 1) {
    fleeingState.value = true; //数量大于1，开启弹窗输入
  }
  for (let i = 0; i < val; i++) {
    fleeingList.value.push({
      number: i + 1, //件数
      packageCode: null, //输入框
    });
  }
};
// 少货编辑
const moneyBtnA = () => {
  if (!Indexform.value.number) {
    ElMessage({
      message: '请输入少货数量',
      type: 'warning',
    });
    return;
  }
  ShortageState.value = true; //开启弹窗输入
};
// 窜货编辑
const moneyBtnB = () => {
  if (!Indexform.value.number) {
    ElMessage({
      message: '请输入窜货数量',
      type: 'warning',
    });
    return;
  }
  fleeingState.value = true; //开启弹窗输入
};

// 是否显示处理结果
const Processingrelease = () => {
  Indexform.value.result = ''; //每次切换处理方先重置
  ProcessingList.value = []; //重置填写好的处理结果
  console.log(Indexform.value.processor, 'Indexform.value.processor');
  if (Indexform.value.processor) {
    if (Indexform.value.processor.length == 1 && Mydata.value.id == Indexform.value.processor[0]) {
      ProcessingreleaseState.value = true; //显示处理放
    } else {
      ProcessingreleaseState.value = false; //关闭处理方
    }
  }
};

// 统计包件个数
const Statistics = () => {
  // 订单统计包件个数
  if (identifying.value == 1) {
    NumberPackages.value = 0;
    PackageInfo.value.map(res => {
      if (res.packageCode) {
        NumberPackages.value++;
      }
    });
  } else {
    // 零担统计包件个数
    NumberPackages.value = 0;
    PackageInfo.value.map(res => {
      console.log(res);
      if (res.waybillNumber) {
        NumberPackages.value++;
      }
    });
  }
};

// 查询包件信息自动回显
const ChangePackageInfo = (val, index) => {
  // 判断是否有一样的包件

  if (identifying.value == '2') {
    Statistics(); //调用统计包件信息
    return;
  } else {
    if (!val) {
      return;
    }
    Statistics(); //调用统计包件信息
    if (!NumberPackages.value) {
      if (!val) {
        PackageInfo.value[index].orderCode = ''; //订单自编码
        PackageInfo.value[index].waybillNumber = ''; //运单号
        PackageInfo.value[index].orderId = ''; //运单号
        PackageInfo.value[index].brandName = ''; //品牌
        Indexform.value.first = ''; //一级品
        Indexform.value.secondary = ''; //二级品
        Indexform.value.waybillMall = ''; //客户名称（运单商场）
        Indexform.value.typeServiceName = ''; //合作模式
        return;
        // 如果输入框里面没有值就不请求
      }
    }

    // if (NumberPackages.value > 1) {
    //   const found = PackageInfo.value
    //     .filter(item => item.packageCode !== val)
    //     .some(item => item.packageCode === val);

    //   if (found) {
    //     console.log('false');
    //     ElMessage({
    //       message: '存在重复包条码',
    //       type: 'warning',
    //     });
    //     return;
    //   }
    // }

    Statistics(); //调用统计包件信息
    let data = {
      packageCode: val,
    };
    $_getAbnormalPackage(data).then(res => {
      console.log(res, '包件信息');
      console.log(res.data.data, '包件信息');
      if (res.data.data.length) {
        TrainnumberList.value = [];
        if (groundlineType.value == 5 || groundlineType.value == 6) {
          //当发现节点为配送装车和配送签收的时候进行数据处理
          //筛选出车次号
          //driverName配送司机
          //taskTime配送时间
          //trainNumber车次号
          //vehicleName车牌
          res.data.data.forEach(item => {
            item.deliver.forEach(itemChid => {
              TrainnumberList.value.push({
                label: itemChid.trainNumber,
                value: itemChid.trainNumber,
              }); //车次号
              DeliveryprocessData.value.push(itemChid);
            });
          });
          // 存储时间
          console.log(TrainnumberList.value, '车次号');
        }
        // 车次号处理
        if (groundlineType.value == 3) {
          res.data.data.forEach(item => {
            console.log(item, 'item');
            item.trunklines.forEach(itemChid => {
              console.log(itemChid, 'itemChid');
              TrainnumberList.value.push({
                label: itemChid.trainNumber,
                value: itemChid.trainNumber,
              }); //车次号
              MainlineUnloadingData.value.push(itemChid);
            });
          });
          console.log(TrainnumberList.value, '车次号');
        }

        console.log(NumberPackages.value, 'NumberPackages.value ');
        console.log(PackageInfo.value, 'PackageInfo.value');
        const packageData = res.data.data[0];
        if (NumberPackages.value > 1) {
          let mallName = PackageInfo.value.find(item => item.mallName).mallName;
          console.log(mallName, '筛选出来的值');
          if (mallName != packageData.mallName) {
            ElMessageBox.confirm('请选择运单商场一致的包条码!', 'Warning', {
              confirmButtonText: '确定',
              type: 'warning',
            })
              .then(() => {
                return;
              })
              .catch(() => {
                ElMessage({
                  type: 'info',
                  message: '请重新输入新包条码',
                });
              });
            return;
          }
        }
        console.log('跑到这里来了');
        // 如果已经有一条数据了，后面运单商场必须和后面的一样
        console.log(packageData, '获取的第一个参数');
        PackageInfo.value[index].orderCode = packageData.orderCode; //订单自编码
        PackageInfo.value[index].waybillNumber = packageData.waybillNumber; //运单号
        PackageInfo.value[index].orderId = packageData.orderId; //运单号
        PackageInfo.value[index].brandName = packageData.brandName; //品牌
        PackageInfo.value[index].mallName = packageData.mallName; //运单商场
        PackageInfo.value[index].state = false; //状态
        const results = res.data.data.filter(item => {
          return item.workOrderId && item.workOrderNumber;
        });
        console.log(results, '筛选后的结果');
        if (results.length > 0) {
          HistoricalPackageList.value = results;
          PackageInfo.value[index].state = true; //状态
        } else {
          PackageInfo.value[index].state = false; //状态
        }
        // 确保在没有满足条件的元素时，不执行 HistoricalPackageList 和 PackageInfo 的赋值操作
        Indexform.value.first = packageData.firsts; //一级品
        Indexform.value.secondary = packageData.second; //二级品
        Indexform.value.waybillMall = packageData.mallName; //客户名称（运单商场）
        Indexform.value.typeServiceName = packageData.typeServiceName
          ? packageData.typeServiceName
          : ''; //合作模式
      }
      // packageCode; //包件码
      // //订单自编码
      // orderCode: orderId; //运单号
      // workOrderId; //工单id
      // workOrderNumber; //工单名称

      console.log(PackageInfo.value, '处理好的参数');
    });
  }
};

// 查看历史包件
const historicalPackages = val => {
  dialogHistoricalPackage.value = true; //打开历史包件弹窗
  HistorIndex.value = val;
  console.log(val);
};
// 历史包件确定选择
const HistoricalPackage = val => {
  let info = HistoricalPackageList.value.find(obj => obj.workOrderId == val);
  console.log(info);
  PackageInfo.value[HistorIndex.value].orderCode = info.orderCode; //订单自编码
  PackageInfo.value[HistorIndex.value].waybillNumber = info.waybillNumber; //运单号
  PackageInfo.value[HistorIndex.value].orderId = info.orderId; //运单号
  PackageInfo.value[HistorIndex.value].brandName = info.brandName; //品牌
  dialogHistoricalPackage.value = false; //关闭历史包件弹窗

  PackageInfo.value[HistorIndex.value].relatedWorkOrdersId = info.workOrderId;
  console.log(PackageInfo.value, '处理好的参数');
};
// 历史包件里面的查看
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 isShowFormItem1 = computed(() => {
  return ['2'].includes(groundlineType.value);
});
// 对调查经过输入框进行处理
const isShowFormItem2 = computed(() => {
  return ['2'].includes(groundlineType.value);
});
const isShowFormItem3 = computed(() => {
  return ['3', '4', '5', '6', '7'].includes(groundlineType.value);
});
const isShowFormItem4 = computed(() => {
  return ['5', '6', '7'].includes(groundlineType.value);
});
</script>

<style scoped lang="scss">
.IndexFrom {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  border: 1px solid #ccc;
  .el-form-item {
    display: flex;
    align-items: flex-start;
    margin: 0;
    margin-bottom: 18px;
    flex: 1 0 30%;
    :deep(.el-form-item__label) {
      width: 100px !important;
      justify-content: flex-start;
    }
  }
  :deep(.el-form-item__content) {
    height: 100%;
    width: 70% !important;
    flex: none;
    .el-input {
      height: 100% !important;
      display: flex;
      align-items: center;
    }
  }
  .el-input__wrapper {
    height: 32px !important;
  }
  :deep(.el-input) {
    width: 100% !important;
  }
  :deep(.el-input__wrapper) {
    height: 30px !important;
  }
  :deep(.el-select) {
    width: 100%;
  }
  :deep(.el-form-item__label) {
    margin-left: 20px;
  }
}
.el_clzr {
  margin-top: 40px;

  :deep(.el-select) {
    width: 100%;
  }
  :deep(.el-input) {
    height: 38px;
  }
  :deep(.el-form-item__label) {
    margin-left: 20px;
    font-size: 14px;
    width: 100px !important;
    justify-content: flex-start;
  }
  .el-form-item {
    margin: 0;
    margin-bottom: 34px;
  }
  :deep(.el-input__wrapper) {
    height: 35px !important;
  }
  :deep(.el-form-item__content) {
    height: 100%;
    width: 90% !important;
    flex: none;
    .el-input {
      height: 100% !important;
      display: flex;
      align-items: center;
    }
  }
}
.Transport_damage_photos {
  flex-direction: column;
  display: flex;
  margin-top: 20px;
  .title {
    font-weight: 500;
    width: 100px;
    display: block;
    margin-bottom: 10px;
    font-size: 14px;
  }
}
.dialog-footer {
  margin-top: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 0 10px;
  box-sizing: border-box;
  padding-right: 36px;
}
.investigate {
  :deep(.el-form-item__content) {
    width: 90% !important;
    box-sizing: border-box;
  }
}
.ShortageStatenum {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .title {
    width: 80px;
  }
  .remove {
    width: 47px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #ff0000;
  }
}
.moneyNum {
  display: flex;
  flex: 1;
  .el_btn {
    width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ccc;
    margin-left: 3px;
    border-radius: 4px;
    cursor: pointer;
  }
}
.ResponsibilityBox {


  width: 100%;
  display: flex;
  flex-direction: column;
  :deep(.asterisk-left) {
    .el-form-item__label {
      width: auto !important;
    }
  }
  .leftbox {
    display: flex;
    justify-content: space-between;
    width: 100%;
    .el_zb {
      width: 140px;
      margin-right: 50px;
      text-align: right;

      :deep(.el-form-item__label) {
        width: auto !important;
      }
      :deep(.el-input) {
        margin-left: 10px;
        text-align: right;
      }
      :deep(.el-form-item__content) {
        flex-wrap: nowrap;
        position: relative;
        .percentage {
          position: absolute;
          right: 11px;
        }
      }
    }
    .illustrate {
      width: 50%;
    }
  }
  .maxBox {
    display: flex;
    align-items: flex-start;
    width: 30%;
    margin-right: 16px;
    font-size: 14px;
    .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;
  }
}
.ResponsibilityBoxS {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  .el_packBtn {
    margin-top: 10px;
  }
  .leftbox {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-top: 10px;
  }
  .maxBox {
    display: flex;
    align-items: center;
    width: 30%;
    margin-right: 20px;

    :deep(.el-form-item) {
      margin: 0;
      margin-right: 10px;

      font-size: 12px;
      .el-form-item__label {
        margin: 0;
        width: auto !important;
      }
    }
    .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;
    align-items: center;
  }
}
:deep(.PackageInformation) {
  margin-bottom: 10px;
  width: 100%;
  border-left: none;
  .el-tabs__header {
  }
  .el-tabs__content {
    padding-top: 0;
  }
}
.NumTotal {
  width: 30%;
  margin-top: 10px;
  display: flex;
  align-items: center;
  span {
    width: 120px;
    font-size: 14px;
    border: 1px solid #ccc;
    display: flex;
    width: auto;
    padding: 4px 12px;
  }
}
.Proportion {
  margin-top: 16px;
  .title {
    font-size: 14px;
    border: 1px solid #ccc;
    width: auto;
    padding: 4px 12px;
  }
}

:deep(.is-active) {
  border-bottom: 1px solid #e4e7ed !important;
}
:deep(.topClass) {
  border-bottom: none;
  .el-tabs__content {
    padding: 0;
  }
}
.foot_btn {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translate(0, -50%);
  width: 100%;
  height: 40px;
  background-color: #ffffff;
  border-top: 1px solid #fff;
  box-shadow: 3px -1px 1px #ccc;
  display: flex;
  align-items: center;
  padding-left: 10px;
}
:deep(.el-card__body) {
  // margin-bottom: 50px;
}
:deep(.el-upload-dragger) {
  display: flex;
  align-items: center;
  justify-content: center;
}
.box-card {
  height: 100% !important;
  overflow-y: scroll;
}
:deep(.selector) {
  .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-bottom: 20px;
      height: 30px;
      width: 48%;
      justify-content: space-between;
      .payment_right {
        display: flex;
        :deep(.el-input) {
          height: 100% !important;
        }
      }
      span {
        display: block;
        color: #606266;
        font-size: 16px;
        margin-right: 8px;
        display: flex;
        align-items: center;
      }
    }
  }

  .lptime,
  .ZFlptime {
    display: flex;
    .name {
      width: 10%;
      color: #606266;
    }
    .el-input {
      width: auto;
    }
    :deep(.el-input--prefix) {
      width: 200px;
    }
  }
  .ZFlptime {
    margin: 10px 0;
  }
}
.Paymentname {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #bfbfbf;
  margin-left: 2px;
  border-radius: 4px;
  font-size: 14px;
  padding: 10px;
  cursor: pointer;
  width: 140px;
  margin: 0 10px;
  overflow: hidden;
}
.Paymentname:hover {
  border: 1px solid #172e60;
}
.el_Processingresults {
  margin-top: 12px;
}
.el_PaymentUnit {
  margin: 0 4px;
}
:deep(.el-input-number) {
  width: 180px !important;
}
.Investigationprocess {
  height: auto !important;
  align-items: flex-start !important;
  :deep(.el-form-item__content) {
    width: 90% !important;
  }
}
.el_tool {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  span {
    font-size: 14px;
    border: 1px solid #ccc;
    padding: 4px 20px;
    color: #30316e;
    font-weight: normal;
  }
}
.el_nint {
  width: 100%;
}
:deep(.el_inputTop) {
  margin-bottom: 0 !important;
  margin: 5px 0 !important;
}
:deep(.el_Exception) {
  .el-form-item__content {
    // width: 120px !important;
  }
}
:deep(.el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before) {
  color: #ff0000;
}
.footer_el {
  padding-right: 0;
  padding: 0;
}
:deep(#avue-view) {
  background-color: #fff !important;
}
.page_loading {
  height: 100%;
}
.el_btn_remove {
  // padding-top: 6px;
}
</style>
