<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #seller>
        <div style="width: 100%">
          <el-form-item prop="sellCorporationId">
            <el-select v-model="formData.data.sellCorporationId" style="width: 100%" filterable>
              <el-option v-for="item in corporationList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="8">
              <el-form-item label="地址" prop="sellCountryName">
                <el-input v-model="formData.data.sellCountryName" placeholder="请输入国家" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label=" " prop="sellProvinceName">
                <el-input v-model="formData.data.sellProvinceName" placeholder="请输入省/州" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label=" " prop="sellCityName">
                <el-input v-model="formData.data.sellCityName" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="24">
              <el-form-item prop="sellAddress">
                <el-input v-model="formData.data.sellAddress" type="textarea">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="8">
              <el-form-item label="联系人" prop="sellContactName">
                <el-input v-model="formData.data.sellContactName" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label=" " prop="sellContactNumber">
                <el-input v-model="formData.data.sellContactNumber" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #buyer>
        <div style="width: 100%">
          <div style="width: 100%">
            <!-- <el-form-item prop="buyCorporationId">
              <el-select
                v-model="formData.data.buyCorporationId"
                style="width: 100%"
                @change="changeCustomer"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item prop="buyCorporationId">
              <el-select v-model="formData.data.buyCorporationId" filterable remote reserve-keyword placeholder="请输入关键字" remote-show-suffix
                         :remote-method="remoteMethod" :loading="loadingSearch" @input="remoteMethod" style="width: 100%" @change="changeCustomer"
                         v-if="
                  [30].includes(route.query.processType) ||
                  !route.query.processType
                ">
                <el-option v-for="item in customerList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="formData.data.buyCorporationName" disabled v-else style="width: 100%">
              </el-select>
            </el-form-item>
            <el-row style="margin-top: 20px; width: 100%">
              <el-col :span="6">
                <el-form-item label="地址" prop="countryId">
                  <el-select v-model="formData.data.countryId" placeholder="国家" filterable @change="(val) => getCityData(val, '20', true)">
                    <el-option v-for="item in countryData" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label=" " prop="provinceId">
                  <el-select v-model="formData.data.provinceId" placeholder="省/洲" filterable @change="(val) => getCityData(val, '30', true)">
                    <el-option v-for="item in provinceData" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label=" " prop="cityId">
                  <el-select v-model="formData.data.cityId" placeholder="城市" filterable>
                    <el-option v-for="item in cityData" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label=" " prop="buyPostalCode">
                  <el-input v-model="formData.data.buyPostalCode" placeholder="请输入邮编" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-top: 20px; width: 100%">
              <el-col :span="24">
                <el-form-item prop="buyAddress">
                  <el-input v-model="formData.data.buyAddress" type="textarea">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-top: 20px; width: 100%">
              <el-col :span="8">
                <el-form-item label="联系人" prop="buyContactName">
                  <el-autocomplete v-model="formData.data.buyContactName" :fetch-suggestions="querySearchPerson" clearable class="inline-input w-50"
                                   placeholder="请输入联系人" @select="handlePerson">
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label=" " prop="buyContactNumber">
                  <el-input v-model="formData.data.buyContactNumber" placeholder="请输入联系人电话" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </template>
      <template #payment>
        <div style="width: 100%">
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="6">
              <el-form-item label="币种" prop="currency">
                <el-select v-model="formData.data.currency" placeholder="请选择币种" style="width: 100%">
                  <el-option v-for="item in accountCurrency" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="汇率" prop="rate">
                <el-input-number onmousewheel="return false;" v-model="formData.data.rate" placeholder="请输入汇率" style="width: 100%" :precision="4"
                                 :controls="false" :min="0" :max="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="6">
              <el-form-item label="付款方式" prop="paymentMethod">
                <el-select v-model="formData.data.paymentMethod" placeholder="请选择付款方式" style="width: 100%">
                  <el-option v-for="item in fundsPaymentMethod" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="预付比例 (%)" prop="advanceRatio">
                <el-input-number onmousewheel="return false;" v-model="formData.data.advanceRatio" placeholder="请输入预付比例" style="width: 100%"
                                 :precision="2" :controls="false" :min="0" :max="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="18">
              <el-form-item label="付款条件" prop="remark">
                <el-input v-model="formData.data.remark" :rows="2" type="textarea" placeholder="请输入付款条件" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="9">
              <el-form-item label="收款账号" prop="shroffAccountId">
                <el-select v-model="formData.data.shroffAccountId" placeholder="请选择收款账号" style="width: 100%" @change="changeShroffAccount">
                  <el-option v-for="item in accountList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="  ">
                <el-button type="primary" @click="changeActiveName" text>
                  <span v-if="activeName == '1'">收起</span>
                  <span v-else>展开</span>
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="width: 100%; margin-top: 34px">
            <el-collapse v-model="activeName" class="hideCollapse" accordion>
              <el-collapse-item title="" name="1">
                <el-row style="width: 100%">
                  <el-col :span="9">
                    <el-form-item label="Beneficiary Name" prop="beneficiaryName">
                      <el-input v-model="formData.data.beneficiaryName" placeholder="请输入Beneficiary Name" />
                    </el-form-item>
                    <div style="height: 20px"></div>
                    <el-form-item label="Beneficiary Bank" prop="beneficiaryBank">
                      <el-input v-model="formData.data.beneficiaryBank" placeholder="请输入Beneficiary Bank" />
                    </el-form-item>
                    <div style="height: 20px"></div>
                    <el-form-item label="Beneficiary Bank Address" prop="beneficiaryBankAddress">
                      <el-input v-model="formData.data.beneficiaryBankAddress" placeholder="请输入Beneficiary Bank Address" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="9">
                    <el-form-item label="Beneficiary Account Number" prop="beneficiaryAccountNumber">
                      <el-input v-model="formData.data.beneficiaryAccountNumber" placeholder="请输入Beneficiary Account Number" />
                    </el-form-item>
                    <div style="height: 20px"></div>
                    <el-form-item label="Swift Code" prop="swiftCode">
                      <el-input v-model="formData.data.swiftCode" placeholder="请输入Swift Code" />
                    </el-form-item>
                    <div style="height: 20px"></div>
                    <el-form-item label="Beneficiary Address" prop="beneficiaryAddress">
                      <el-input v-model="formData.data.beneficiaryAddress" placeholder="请输入Beneficiary Address" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </template>
      <template #delivery>
        <div style="width: 100%">
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="6" v-show="showAllData">
              <el-form-item label="报价有效期 (天)" prop="effective">
                <el-input-number onmousewheel="return false;" v-model="formData.data.effective" placeholder="请输入有效期" style="width: 100%"
                                 :precision="0" :controls="false" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="交货期限" prop="deliveryTime">
                <el-date-picker v-model="formData.data.deliveryTime" type="date" placeholder="请选择交货期限" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="运输方式" prop="transportMethod">
                <el-select v-model="formData.data.transportMethod" placeholder="请选择运输方式" style="width: 100%">
                  <el-option v-for="item in shippingMethod" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="运输说明" prop="transportRemark">
                <el-input v-model="formData.data.transportRemark" placeholder="请输入运输说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #commodity>
        <div style="width: 100%">
          <el-button type="primary" @click="openProductCompany = true" plain>标准产品库</el-button>
          <el-button type="primary" @click="clickCustomerProduct()" plain>客户产品库</el-button>
          <el-table :data="formData.data.contractProductList" style="width: 100%; margin-top: 16px">
            <el-table-column label="商品图片" width="80">
              <template #default="{ row }">
                <div v-if="row.fileUrl">
                  <img :src="row.fileUrl" class="pic" @click="onPicture(row.fileUrl)" />
                </div>
                <div v-else></div>
              </template>
            </el-table-column>
            <el-table-column prop="productCnName" label="商品中文名" min-width="130" />
            <el-table-column label="商品英文名" min-width="180">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.productName'" :rules="rules.productName" :inline-message="true"
                                class="shrinkPadding">
                    <el-input v-model="row.productName" placeholder="请输入商品名称" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="尺寸 cm*cm*cm" width="140">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.productModel'" :rules="rules.productModel" :inline-message="true"
                                class="shrinkPadding">
                    <el-input v-model="row.productModel" placeholder="请输入" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="包装方式" width="180">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.packMethod'" :rules="rules.packMethod" :inline-message="true"
                                class="shrinkPadding">
                    <el-input v-model="row.packMethod" placeholder="请输入" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="130">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true"
                                class="shrinkPadding">
                    <el-input-number onmousewheel="return false;" v-model="row.quantity" placeholder="请输入" style="width: 100%" :precision="0"
                                     :controls="false" :min="0" @change="calculationAmount('quantity')" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="140" v-if="showAllData">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.price'" :rules="rules.price" :inline-message="true" class="shrinkPadding">

                    <div style="display:flex;">
                      <el-input-number onmousewheel="return false;" v-model="row.price" placeholder="请输入" style="width: 100%" :precision="2"
                                       :controls="false" :min="0" @change="calculationAmount()" />
                      <el-popover placement="top-start" :width="400" trigger="hover" @show="showEcharts(row,$index)">
                        <template #default>
                          <div>
                            <div>
                              <img src="@/assets/images/money1.png" alt="" class="img" /> <span
                                    style="font-size:14px;font-weight:700;color:#000">销售指导价：</span>
                              <div style="padding:5px 0px 0px 20px">
                                {{row.currency}} {{moneyFormat(row.salePrice,2)}}
                              </div>
                            </div>
                            <div style="margin-top:15px">
                              <img src="@/assets/images/money2.png" alt="" class="img" /> <span
                                    style="font-size:14px;font-weight:700;color:#000">客户近期购买价格：</span>
                              <div style="padding:5px 0px 0px 20px">
                                <div v-for="item in row.customerContractProductList">
                                  <span>{{item.createTime.slice(0,10)}} </span>
                                  <span style="margin-left:40px">{{item.code}} </span>
                                  <span style="margin-left:40px"> {{item.currency}} {{moneyFormat(item.price,2)}} </span>
                                </div>
                              </div>
                            </div>
                            <div style="margin-top:15px">
                              <img src="@/assets/images/money3.png" alt="" class="img" /> <span
                                    style="font-size:14px;font-weight:700;color:#000">产品近期销售价格：</span>
                              <div style="padding:5px 0px 0px 20px">
                                <div v-for="item in row.contractProductList">
                                  <span>{{item.createTime.slice(0,10)}} </span>
                                  <span style="margin-left:40px">{{item.code}} </span>
                                  <span style="margin-left:40px">{{item.currency}} {{moneyFormat(item.price,2)}} </span>
                                </div>
                              </div>
                            </div>
                            <div :ref="row.productId+$index" style="height:180px">
                            </div>
                          </div>
                        </template>
                        <template #reference>
                          <div style="margin-left:10px;cursor:pointer;position:relative;top:4px">
                            <el-icon :size="20" color="#85c1a6">
                              <WarningFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-popover>
                    </div>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="贸易方式" width="140" v-if="showAllData">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProductList.' + $index + '.tradeMethods'" :rules="rules.tradeMethods" :inline-message="true"
                                class="shrinkPadding">
                    <el-select v-model="row.tradeMethods" placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in tradeMethods" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="amount" :label="'金额 ( ' + formData.data.currency + ' )'" width="130" v-if="showAllData" />
            <el-table-column label="操作" width="60" align="center" fixed="right">
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="handleRemove($index, row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #file>
        <div style="width: 100%">
          <el-upload v-model:fileList="formData.data.fileList" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com" :data="uploadData" multiple
                     :before-upload="uploadFile" :on-success="handleSuccess" :on-preview="onPreviewFile">
            <el-button type="primary" plain>选择</el-button>
          </el-upload>
        </div>
      </template>
      <template #indication>
        <div style="width: 100%">
          <el-upload v-model:fileList="formData.data.packageFileList" action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                     :data="indicationUploadData" multiple :before-upload="indicationUploadFile" :on-success="handleSuccess"
                     :on-preview="onPreviewFile">
            <el-button type="primary" plain>选择</el-button>
          </el-upload>
        </div>
      </template>
      <template #otherCharge>
        <div style="width: 100%">
          <el-button type="primary" @click="clickAdd()">添加行</el-button>
          <el-table :data="formData.data.contractProjectList" style="width: 100%; margin-top: 16px">
            <el-table-column label="收费项目" width="220">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProjectList.' + $index + '.payName'" :rules="rules.payName" :inline-message="true">
                    <el-autocomplete v-model="row.payName" :fetch-suggestions="querySearch" clearable class="inline-input w-50"
                                     placeholder="请输入收费项目" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProjectList.' + $index + '.remark'">
                    <el-input v-model="row.remark" placeholder="请输入备注" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="'金额 ( ' + formData.data.currency + ' )'" width="130">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'contractProjectList.' + $index + '.amount'" :rules="rules.amount" :inline-message="true"
                                class="shrinkPadding">
                    <el-input-number onmousewheel="return false;" v-model="row.amount" placeholder="请输入金额" style="width: 100%" :precision="2"
                                     :controls="false" :min="0" @change="totalAmount()" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60" align="center" fixed="right">
              <template #default="{ $index }">
                <el-button type="primary" link @click="handleDelete($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #offerMoney>
        <div style="width: 100%; display: flex">
          <div style="width: calc(100% - 190px)"></div>
          <div style="width: 130px; padding: 0 12px">
            <el-form-item label="合同总金额" prop="amount" class="shrinkPadding">
              <el-input v-model="formData.data.amount" placeholder="合同总金额" disabled />
            </el-form-item>
          </div>
        </div>
      </template>
      <template #shipment>
        <!-- <div style="width: 100%">
          <el-table
            :data="formData.data.contractShipmentList"
            style="width: 100%; margin-top: 16px"
          >
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column label="出货日期" width="220">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item
                    :prop="'contractShipmentList.' + $index + '.shipmentTime'"
                    :rules="rules.shipmentTime"
                    :inline-message="true"
                  >
                    <el-date-picker
                      v-model="row.shipmentTime"
                      type="date"
                      placeholder="请选择出货日期"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="160">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item
                    :prop="'contractShipmentList.' + $index + '.quantity'"
                    :inline-message="true"
                  >
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.quantity"
                      placeholder="请输入数量"
                      style="width: 100%"
                      :precision="0"
                      :controls="false"
                      :min="0"
                      @change="calculationAmount()"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="操作"
              width="120"
              fixed="right"
            >
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="clickSplit(row)"
                  >拆分</el-button
                >
                <el-button type="primary" link @click="clickDelete($index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div> -->
        <div style="width: 100%">
          <el-row>
            <el-col :span="10" style="border: 1px solid #ebeef5; padding: 10px">
              <el-form-item label="出货日期" required>
                <el-date-picker v-model="formData.data.shipmentTime" type="date" placeholder="请选择出货日期" value-format="YYYY-MM-DD" />
              </el-form-item>
              <el-table :data="formData.data.contractWaitShipmentList" @selection-change="handleSelectionChange" ref="tableDom"
                        style="margin: 15px 0">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="productCode" label="商品编号" />
                <el-table-column prop="productName" label="商品名称" />
                <el-table-column label="出货数量" width="160">
                  <template #default="{ row, $index }">
                    <div style="width: 100%">
                      <el-form-item :prop="
                          'contractWaitShipmentList.' + $index + '.quantity'
                        " :inline-message="true">
                        <el-input-number onmousewheel="return false;" v-model="row.quantity" placeholder="请输入数量" style="width: 100%" :precision="0"
                                         :controls="false" :min="0" />
                      </el-form-item>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="waitQuantity" label="剩余数量" />
              </el-table>
              <div style="text-align: center">
                <el-button type="primary" @click="handleAddShipment">添加</el-button>
              </div>
            </el-col>
            <el-col :span="14">
              <div style="padding: 10px; margin-top: 77px">
                <el-table :data="formData.data.contractShipmentList" :span-method="objectSpanMethod">
                  <el-table-column prop="shipmentTime" label="出货日期" width="155">
                  </el-table-column>
                  <el-table-column prop="productCode" label="商品编码" />
                  <el-table-column prop="productName" label="商品名称" />
                  <el-table-column prop="quantity" label="出货数量" width="160">
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="80" fixed="right">
                    <template #default="{ row, $index }">
                      <el-button type="primary" link @click="clickDelete($index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
    </byForm>

    <el-dialog v-if="openProductCompany" v-model="openProductCompany" title="公司产品库" width="90%" append-to-body>
      <CompanyProduct :selectStatus="true" @selectProduct="selectProduct"></CompanyProduct>
    </el-dialog>

    <el-dialog v-if="openProductCustomer" v-model="openProductCustomer" title="客户产品库" width="90%" append-to-body>
      <CustomerProduct :selectStatus="true" :buyCorporationId="formData.data.buyCorporationId" @selectProduct="selectProduct"></CustomerProduct>
    </el-dialog>
  </div>
</template>

<script setup>
import byForm from "@/components/byForm/index";
import CompanyProduct from "@/views/EHSD/productLibrary/companyProduct/index";
import CustomerProduct from "@/views/EHSD/productLibrary/customerProduct/index";
import { ElMessage } from "element-plus";
import selectCity from "@/components/selectCity/index.vue";
import { useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
import { v4 as uuidv4 } from "uuid";
import * as echarts from "echarts";

const userInfo = useUserStore();
const showAllData = ref(true);
const route = useRoute();
const { proxy } = getCurrentInstance();
const innerMethod = ref([]);
const outsideMethod = ref([]);
const accountCurrency = ref([]);
const fundsPaymentMethod = ref([]);
const tradeMethods = ref([]);
const shippingMethod = ref([]);
const templateList = ref([]);
const corporationList = ref([]);
const customerList = ref([]);
const accountList = ref([]);
const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);
const customerUserList = ref([]);
const openProductCompany = ref(false);
const openProductCustomer = ref(false);
const activeName = ref("1");
const formData = reactive({
  data: {
    currency: "",
    amount: null,
    contractProductList: [],
    contractProjectList: [],
    fileList: [],
    packageFileList: [],
    contractShipmentList: [],
    contractWaitShipmentList: [],
  },
});
const submit = ref(null);
const optionTwo = reactive({
  data: {
    tooltip: {
      trigger: "axis",
    },
    // legend: {
    //   data: ["价格"],
    // },
    grid: {
      left: "3%",
      right: "4%",
      top: "10%",
      bottom: "3%",
      containLabel: true,
    },
    // toolbox: {
    //   feature: {
    //     saveAsImage: {},
    //   },
    // },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: [],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "价格",
        type: "line",
        data: [],
      },
    ],
  },
});
const showEcharts = (row, index) => {
  let myChart = null;
  myChart = echarts.init(proxy.$refs[row.productId + index]);
  window.addEventListener("resize", () => {
    myChart.resize();
  });
  if (row.contractProductListOne && row.contractProductListOne.length > 0) {
    optionTwo.data.xAxis.data = row.contractProductListOne.map((item) => {
      return item.createTime.slice(0, 10);
    });
    optionTwo.data.series[0].data = row.contractProductListOne.map((item) => {
      return item.price;
    });
  } else {
    optionTwo.data.xAxis.data = [];
    optionTwo.data.series[0].data = [];
  }
  myChart.setOption(optionTwo.data);
  myChart.resize();
};

const judgeStatus = () => {
  if (route.query.processType == 20 || route.query.processType == 10) {
    return true;
  }
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter(
      (item) => item.status === 2 && item.nodeType !== 1
    );
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const uploadData = ref({});
const indicationUploadData = ref({});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "合同模板",
      label: "",
      isShow: showAllData.value,
    },
    {
      type: "select",
      label: "选择合同模板",
      prop: "contractTemplateId",
      data: templateList.value,
      fn: (val) => {
        changeTemplate(val);
      },
      isShow: showAllData.value,
    },
    {
      type: "slot",
      slotName: "seller",
      label: "卖方信息",
      itemWidth: 50,
      isShow: showAllData.value,
    },
    {
      type: "slot",
      slotName: "buyer",
      label: "买方信息",
      itemWidth: 50,
      isShow: showAllData.value,
    },

    {
      type: "title",
      title: "付款信息",
      isShow: showAllData.value,
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "payment",
      label: "",
      isShow: showAllData.value,
    },

    {
      type: "title",
      title: "交付信息",
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "delivery",
      label: "",
    },
    {
      type: "title",
      title: "商品信息",
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "commodity",
      label: "",
    },
    {
      type: "slot",
      slotName: "file",
      label: "交接单",
    },
    {
      type: "slot",
      slotName: "indication",
      label: "包装指示",
    },

    {
      type: "title",
      title: "其他收费项目",
      isShow: showAllData.value,
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "otherCharge",
      label: "",
      isShow: showAllData.value,
    },
    {
      type: "slot",
      slotName: "offerMoney",
      isShow: showAllData.value,
    },

    {
      type: "title",
      title: "出货计划",
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "shipment",
      label: "",
    },
  ];
});
const rules = ref({
  // contractTemplateId: [
  //   { required: true, message: "请选择合同模板", trigger: "change" },
  // ],
  sellCorporationId: [
    { required: true, message: "请选择公司", trigger: "change" },
  ],
  buyCorporationId: [
    { required: true, message: "请选择公司", trigger: "change" },
  ],
  countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  sellAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  buyAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  buyContactName: [
    { required: true, message: "请输入联系人", trigger: ["change", "blur"] },
  ],
  buyContactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  productModel: [
    { required: true, message: "请输入尺寸 cm*cm*cm", trigger: "blur" },
  ],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入单价", trigger: "blur" }],
  // packMethod: [{ required: true, message: "请输入包装方式", trigger: "blur" }],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  payName: [
    { required: true, message: "请输入收费项目", trigger: ["change", "blur"] },
  ],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  effective: [{ required: true, message: "请输入报价有效期", trigger: "blur" }],
  // deliveryTime: [
  //   { required: true, message: "请选择交货期限", trigger: "change" },
  // ],
  paymentMethod: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  advanceRatio: [
    { required: true, message: "请输入预付比例", trigger: "blur" },
  ],
  // shroffAccountId: [
  //   { required: true, message: "请选择收款账号", trigger: "change" },
  // ],
  beneficiaryName: [
    { required: true, message: "请输入Beneficiary Name", trigger: "blur" },
  ],
  tradeMethods: [
    { required: true, message: "请选择贸易方式", trigger: "change" },
  ],
  transportMethod: [
    { required: true, message: "请选择运输方式", trigger: "change" },
  ],
  // transportRemark: [
  //   { required: true, message: "请输入运输说明", trigger: "blur" },
  // ],
  remark: [{ required: true, message: "请输入付款条件", trigger: "blur" }],
  rate: [{ required: true, message: "请输入汇率", trigger: "blur" }],
});
const getDict = () => {
  proxy
    .getDictOne([
      "inner_packaging_method_ehsd",
      "outside_packaging_method_ehsd",
      "account_currency",
      "funds_payment_method",
      "trade_mode",
      "shipping_method",
    ])
    .then((res) => {
      innerMethod.value = res["inner_packaging_method_ehsd"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      outsideMethod.value = res["outside_packaging_method_ehsd"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      accountCurrency.value = res["account_currency"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      fundsPaymentMethod.value = res["funds_payment_method"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      tradeMethods.value = res["trade_mode"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      shippingMethod.value = res["shipping_method"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
  proxy
    .post("/contractTemplate/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      templateList.value = res.rows.map((item) => {
        return {
          ...item,
          label: item.templateName,
          value: item.id,
        };
      });
    });
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    corporationList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });

  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      accountList.value = res.rows.map((item) => {
        return {
          ...item,
          label: item.alias,
          value: item.id,
        };
      });
    });
};
getDict();
const changeTemplate = (val) => {
  formData.data.sellCorporationId = "";
  formData.data.sellContactName = "";
  formData.data.sellContactNumber = "";
  formData.data.sellCountryName = "";
  formData.data.sellProvinceName = "";
  formData.data.sellCityName = "";
  formData.data.sellAddress = "";
  if (val) {
    proxy.post("/contractTemplate/detail", { id: val }).then((res) => {
      formData.data.sellCorporationId = res.corporationId;
      if (res.corporationId) {
        proxy
          .post("/corporation/detail", { id: res.corporationId })
          .then((detailCorporation) => {
            proxy
              .post("/customizeArea/list", { parentId: "0" })
              .then((resCountry) => {
                let sellCountryData = resCountry.filter(
                  (item) => item.id === detailCorporation.countryId
                );
                if (sellCountryData && sellCountryData.length > 0) {
                  formData.data.sellCountryName =
                    sellCountryData[0].chineseName;
                } else {
                  formData.data.sellCountryName = "";
                }
              });
            if (detailCorporation.countryId) {
              proxy
                .post("/customizeArea/list", {
                  parentId: detailCorporation.countryId,
                })
                .then((resProvince) => {
                  let sellProvinceData = resProvince.filter(
                    (item) => item.id === detailCorporation.provinceId
                  );
                  if (sellProvinceData && sellProvinceData.length > 0) {
                    formData.data.sellProvinceName = sellProvinceData[0].name;
                  } else {
                    formData.data.sellProvinceName = "";
                  }
                });
            } else {
              formData.data.sellProvinceName = "";
            }
            if (detailCorporation.provinceId) {
              proxy
                .post("/customizeArea/list", {
                  parentId: detailCorporation.provinceId,
                })
                .then((resCity) => {
                  let sellCityData = resCity.filter(
                    (item) => item.id === detailCorporation.cityId
                  );
                  if (sellCityData && sellCityData.length > 0) {
                    formData.data.sellCityName = sellCityData[0].name;
                  } else {
                    formData.data.sellCityName = "";
                  }
                });
            } else {
              formData.data.sellCityName = "";
            }
            formData.data.sellAddress = detailCorporation.address;
          });
      }
      formData.data.sellContactName = res.contactName;
      formData.data.sellContactNumber = res.contactNumber;
    });
  }
};
const getCityData = (id, type, isChange) => {
  proxy.post("/customizeArea/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (isChange) {
        formData.data.provinceId = "";
        formData.data.provinceName = "";
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (isChange) {
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else {
      countryData.value = res;
    }
  });
};
getCityData("0");
let auxiliaryData = ref([
  {
    label: "最近合同",
    data: [],
  },
  {
    label: "产品价格",
    data: [],
  },
]);
const emit = defineEmits(["auxiliaryChange"]);
const getDecisionAids = () => {
  let data = {
    buyCorporationId: formData.data.buyCorporationId,
    productIdList: [],
  };
  if (
    formData.data.contractProductList &&
    formData.data.contractProductList.length > 0
  ) {
    data.productIdList = formData.data.contractProductList.map(
      (item) => item.productId
    );
  }
  proxy.post("/contract/decisionAid", data).then((res) => {
    if (res.lastContractList && res.lastContractList.length > 0) {
      auxiliaryData.value[0].data = res.lastContractList.map((item) => {
        return [
          {
            label: "合同编号",
            value: item.code,
            style: {
              color: "#0084FF",
            },
            id: item.id,
            num: 1,
            // fn: () => {},
          },
          {
            label: "下单日期",
            value: item.createTime,
            id: item.id,
            num: 1,
          },
          {
            label: "合同金额",
            value: item.currency + item.amount,
            id: item.id,
            num: 1,
          },
        ];
      });
    } else {
      auxiliaryData.value[0].data = [];
    }
    if (res.productPriceList && res.productPriceList.length > 0) {
      auxiliaryData.value[1].data = res.productPriceList.map((item) => {
        return [
          {
            label: "产品名称",
            value: item.name,
            id: item.id,
            num: 1,
          },
          {
            label: "最近价格",
            value: item.lastPrice,
            id: item.id,
            num: 1,
          },
          {
            label: "历史最高",
            value: item.maxPrice,
            id: item.id,
            num: 1,
          },
          {
            label: "历史最低",
            value: item.minPrice,
            id: item.id,
            num: 1,
          },
        ];
      });
    } else {
      auxiliaryData.value[1].data = [];
    }
    emit("auxiliaryChange", auxiliaryData.value);
  });
};

const changeCustomer = (val) => {
  formData.data.contractProductList = [];
  formData.data.contractWaitShipmentList = [];
  formData.data.contractShipmentList = [];
  formData.data.customerName = "";
  formData.data.customerTel = "";
  if (val) {
    proxy.post("/customer/detail", { id: val }).then(
      (res) => {
        formData.data.buyCorporationName = res.name;
        if (res.customerUserList && res.customerUserList.length > 0) {
          formData.data.buyContactName = res.customerUserList[0].name;
          if (res.customerUserList[0].contactJson) {
            let contactJson = JSON.parse(res.customerUserList[0].contactJson);
            if (contactJson && contactJson.length > 0) {
              formData.data.buyContactNumber = contactJson[0].contactNo;
            }
          }
          customerUserList.value = res.customerUserList.map((item) => {
            return {
              ...item,
              value: item.name,
            };
          });
        }
        // 回填客户的账户信息
        formData.data.beneficiaryName = res.beneficiaryName;
        formData.data.beneficiaryBank = res.beneficiaryBank;
        formData.data.beneficiaryBankAddress = res.beneficiaryBankAddress;
        formData.data.beneficiaryAccountNumber = res.beneficiaryAccountNumber;
        formData.data.swiftCode = res.swiftCode;
        formData.data.beneficiaryAddress = res.beneficiaryAddress;

        formData.data.countryId = res.countryId;
        formData.data.provinceId = res.provinceId;
        formData.data.cityId = res.cityId;
        formData.data.buyPostalCode = res.zipCode;
        formData.data.buyAddress = res.address;
        getCityData(formData.data.countryId, "20");
        if (formData.data.provinceId) {
          getCityData(formData.data.provinceId, "30");
        }
      },
      (err) => {
        console.log(err);
        formData.data.countryId = "";
        formData.data.provinceId = "";
        formData.data.cityId = "";
        formData.data.buyPostalCode = "";
        formData.data.buyAddress = "";
      }
    );
  } else {
    formData.data.countryId = "";
    formData.data.provinceId = "";
    formData.data.cityId = "";
    formData.data.buyPostalCode = "";
    formData.data.buyAddress = "";
  }
  getDecisionAids();
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
const querySearchPerson = (queryString, callback) => {
  const results = queryString
    ? customerUserList.value.filter(createFilter(queryString))
    : customerUserList.value;
  callback(results);
};
const handlePerson = (item) => {
  formData.data.customerTel = item.phone;
};

const selectProduct = (goods) => {
  if (goods && goods.id) {
    // let data = formData.data.contractProductList.filter(
    //   (item) => item.productId === goods.id
    // );
    // if (data && data.length > 0) {
    //   return ElMessage("该产品已添加");
    // }
    let rowId = uuidv4();
    let fileUrl = "";
    if (goods.fileList && goods.fileList.length > 0) {
      fileUrl = goods.fileList[0].fileUrl;
    }
    let packMethod = "";
    if (goods.innerPackMethod) {
      let innerPackMethod = goods.innerPackMethod.split(",");
      innerPackMethod.map((item) => {
        if (packMethod) {
          packMethod =
            packMethod + "," + proxy.dictValueLabel(item, innerMethod.value);
        } else {
          packMethod = proxy.dictValueLabel(item, innerMethod.value);
        }
      });
    }
    if (goods.outerPackMethod) {
      let outerPackMethod = goods.outerPackMethod.split(",");
      outerPackMethod.map((item) => {
        if (packMethod) {
          packMethod =
            packMethod + "," + proxy.dictValueLabel(item, outsideMethod.value);
        } else {
          packMethod = proxy.dictValueLabel(item, outsideMethod.value);
        }
      });
    }
    if (
      formData.data.contractProductList &&
      formData.data.contractProductList.length > 0
    ) {
      formData.data.contractProductList.push({
        fileUrl: fileUrl,
        rowId,
        productId: goods.id,
        productCnName: goods.name,
        productName: goods.nameEnglish,
        productModel:
          goods.productLong + "*" + goods.productWide + "*" + goods.productHigh,
        quantity: null,
        price: null,
        amount: "",
        tradeMethods: "",
        packMethod: packMethod,
      });
    } else {
      formData.data.contractProductList = [
        {
          fileUrl: fileUrl,
          rowId,
          productId: goods.id,
          productCnName: goods.name,
          productName: goods.nameEnglish,
          productModel:
            goods.productLong +
            "*" +
            goods.productWide +
            "*" +
            goods.productHigh,
          quantity: null,
          price: null,
          amount: "",
          tradeMethods: "",
          packMethod: packMethod,
        },
      ];
    }
    changeProductPrice();
    //左侧待出货列表
    formData.data.contractWaitShipmentList.push({
      productCode: goods.code,
      rowId,
      productId: goods.id,
      productName: goods.nameEnglish,
      quantity: null,
      waitQuantity: "",
    });
    ElMessage({
      message: "添加成功！",
      type: "success",
    });
  } else {
    return ElMessage("选择错误");
  }
  getDecisionAids();
};

const changeProductPrice = () => {
  let productIds = formData.data.contractProductList.map((x) => x.productId);
  if (productIds && productIds.length > 0) {
    proxy
      .post("/contract/getProductPriceInfo", {
        productIds: productIds,
        customerId: formData.data.buyCorporationId
          ? formData.data.buyCorporationId
          : "",
      })
      .then((res) => {
        for (let i = 0; i < formData.data.contractProductList.length; i++) {
          const iele = formData.data.contractProductList[i];
          for (const key in res) {
            if (key == iele.productId) {
              iele.salePrice = res[key].price;
              iele.currency = res[key].currency;
              iele.saleCostPrice = res[key].costPrice;
              iele.contractProductList = res[key].contractProductList
                .map((x) => ({
                  createTime: x.createTime,
                  price: x.price,
                  currency: x.currency,
                }))
                .filter((y, index) => index < 3);
              iele.contractProductListOne = res[key].contractProductList.map(
                (x) => ({
                  createTime: x.createTime,
                  price: x.price,
                  currency: x.currency,
                })
              );
              iele.customerContractProductList = res[
                key
              ].customerContractProductList.map((x) => ({
                createTime: x.createTime,
                price: x.price,
                currency: x.currency,
              }));
            }
          }
        }
      });
  }
};
const onPicture = (path) => {
  window.open(path, "_blank");
};
const handleRemove = async (index, row) => {
  formData.data.contractShipmentList =
    formData.data.contractShipmentList.filter(
      (item) => item.rowId !== row.rowId
    );
  formData.data.contractWaitShipmentList =
    formData.data.contractWaitShipmentList.filter(
      (item) => item.rowId !== row.rowId
    );
  await formData.data.contractProductList.splice(index, 1);
  totalAmount();
};
const calculationAmount = (att = "") => {
  nextTick(() => {
    if (
      formData.data.contractProductList &&
      formData.data.contractProductList.length > 0
    ) {
      for (let i = 0; i < formData.data.contractProductList.length; i++) {
        let money = 0;
        money = parseFloat(
          Number(formData.data.contractProductList[i].quantity) *
            Number(formData.data.contractProductList[i].price)
        ).toFixed(2);
        formData.data.contractProductList[i].amount = money;
      }
      // 重新计算待出货数量
      if (att) {
        changeWaitQuantity();
      }
    }
    nextTick(() => {
      totalAmount();
    });
  });
};
const totalAmount = () => {
  let money = 0;
  if (
    formData.data.contractProductList &&
    formData.data.contractProductList.length > 0
  ) {
    for (let i = 0; i < formData.data.contractProductList.length; i++) {
      if (formData.data.contractProductList[i].amount) {
        money = parseFloat(
          Number(money) + Number(formData.data.contractProductList[i].amount)
        ).toFixed(2);
      }
    }
  }
  if (
    formData.data.contractProjectList &&
    formData.data.contractProjectList.length > 0
  ) {
    for (let i = 0; i < formData.data.contractProjectList.length; i++) {
      if (formData.data.contractProjectList[i].amount) {
        money = parseFloat(
          Number(money) + Number(formData.data.contractProjectList[i].amount)
        ).toFixed(2);
      }
    }
  }
  formData.data.amount = money;
};
const clickAdd = () => {
  if (
    formData.data.contractProjectList &&
    formData.data.contractProjectList.length > 0
  ) {
    formData.data.contractProjectList.push({
      payName: "",
      amount: null,
      remark: "",
    });
  } else {
    formData.data.contractProjectList = [
      { payName: "", amount: null, remark: "" },
    ];
  }
};
const handleDelete = async (index) => {
  await formData.data.contractProjectList.splice(index, 1);
  totalAmount();
  getDecisionAids();
};
const querySearch = (queryString, callback) => {
  proxy.post("/quotationPay/page", { payName: queryString }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      res.rows = res.rows.map((item) => {
        return {
          ...item,
          value: item.payName,
        };
      });
      callback(res.rows);
    } else {
      callback([]);
    }
  });
};
const handleSubmit = async () => {
  let status = await submit.value.handleSubmit(() => {});
  if (status) {
    if (
      !(
        formData.data.contractProductList &&
        formData.data.contractProductList.length > 0
      )
    ) {
      ElMessage("请添加至少一件商品");
      return false;
    }
    if (formData.data.fileList && formData.data.fileList.length > 0) {
      for (let i = 0; i < formData.data.fileList.length; i++) {
        if (formData.data.fileList[i].raw.uploadState) {
          ElMessage("文件上传中,请稍后提交");
          return false;
        }
      }
      formData.data.isDeliveryFile = "1";
    } else {
      formData.data.isDeliveryFile = "0";
    }
    if (
      formData.data.packageFileList &&
      formData.data.packageFileList.length > 0
    ) {
      for (let i = 0; i < formData.data.packageFileList.length; i++) {
        if (formData.data.packageFileList[i].raw.uploadState) {
          ElMessage("文件上传中,请稍后提交");
          return false;
        }
      }
      formData.data.isPackFile = "1";
    } else {
      formData.data.isPackFile = "0";
    }
    if (
      formData.data.contractShipmentList &&
      formData.data.contractShipmentList.length > 0
    ) {
      // for (let i = 0; i < formData.data.contractProductList.length; i++) {
      //   let data = formData.data.contractShipmentList.filter(
      //     (item) =>
      //       item.productId === formData.data.contractProductList[i].productId
      //   );
      //   if (data && data.length > 0) {
      //     let quantity = 0;
      //     for (let j = 0; j < data.length; j++) {
      //       quantity = parseFloat(Number(quantity) + Number(data[j].quantity));
      //     }
      //     if (quantity > formData.data.contractProductList[i].quantity) {
      //       ElMessage("出货数量不能大于商品数量");
      //       return false;
      //     }
      //   }
      // }
    } else {
      ElMessage("请添加出货计划");
      return false;
    }
    // 判断产品是否存在变更
    if (
      formData.data.contractProductList &&
      formData.data.contractProductList.length > 0 &&
      formData.data.oldContractProductList &&
      formData.data.oldContractProductList.length > 0
    ) {
      // 当前产品长度
      let len = formData.data.contractProductList.length;
      formData.data.startType = "0";
      if (
        formData.data.contractProductList.length !==
        formData.data.oldContractProductList.length
      ) {
        formData.data.startType = "0";
      } else {
        // 相同的产品长度
        let theSameLen = 0;
        for (let i = 0; i < formData.data.contractProductList.length; i++) {
          const iele = formData.data.contractProductList[i];
          // 在老的产品列表是否有找到相同产品
          let item = formData.data.oldContractProductList.find(
            (x) => x.productId === iele.productId
          );
          // 判断当前产品和老的产品数据是否一致
          if (
            item &&
            item.productName === iele.productName &&
            item.productModel === iele.productModel &&
            item.packMethod === iele.packMethod &&
            Number(item.quantity) === Number(iele.quantity)
          ) {
            theSameLen += 1;
          } else {
            break;
          }
        }
        if (len === theSameLen) {
          formData.data.startType = "1";
        }
      }
    }
    return true;
  } else {
    setTimeout(() => {
      const errorDiv = document.getElementsByClassName("is-error");
      errorDiv[0].scrollIntoView();
    }, 0);
  }
  return status;
};

// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
const clickCustomerProduct = () => {
  if (!formData.data.buyCorporationId) {
    return ElMessage("请先选择客户");
  }
  openProductCustomer.value = true;
};

const loadingSearch = ref(false);
const remoteMethod = (keyword) => {
  if (keyword && typeof keyword === "string") {
    loadingSearch.value = true;
    proxy
      .post("/customer/selPage", { keyword, userId: userInfo.user.userId })
      .then((res) => {
        customerList.value = res.rows.map((x) => ({
          ...x,
          label: x.name,
          value: x.id,
        }));
        loadingSearch.value = false;
      });
  }
  return;
};

const getFormData = () => {
  return proxy.deepClone(formData.data);
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});
const changeShroffAccount = (val) => {
  if (val) {
    let data = accountList.value.filter((item) => item.value === val);
    if (data && data.length > 0) {
      formData.data.beneficiaryName = data[0].beneficiaryName;
      formData.data.beneficiaryBank = data[0].beneficiaryBank;
      formData.data.beneficiaryBankAddress = data[0].beneficiaryBankAddress;
      formData.data.beneficiaryAccountNumber = data[0].beneficiaryAccountNumber;
      formData.data.swiftCode = data[0].swiftCode;
      formData.data.beneficiaryAddress = data[0].beneficiaryAddress;
    }
  }
};
const changeActiveName = () => {
  if (activeName.value) {
    activeName.value = "";
  } else {
    activeName.value = "1";
  }
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const indicationUploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  indicationUploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const clickSplit = (item) => {
  formData.data.contractShipmentList.push({
    productCode: item.code,
    productId: item.productId,
    productName: item.productName,
    shipmentTime: "",
    quantity: null,
  });
};
const clickDelete = (index) => {
  formData.data.contractShipmentList.splice(index, 1);
  changeWaitQuantity();
};

// 判断当前用户有无销售合同页面权限
const isHave = ref(false);
if (userInfo.permissions && userInfo.permissions.includes("contract")) {
  isHave.value = true;
}
const handlePushRoute = (row) => {
  proxy.$router.push({
    name: "Contract",
    query: {
      code: row.value,
    },
  });
};

onMounted(() => {
  checkShow();
  formOption.disabled = judgeStatus();
  if (route.query && route.query.businessId && route.query.processType) {
    let businessId = route.query.businessId;
    proxy.post("/contract/detail", { id: businessId }).then((res) => {
      // if (res && res.dataJson) {
      //   res = { ...res, ...JSON.parse(res.dataJson) };
      // }
      if (!res.fileList) {
        res.fileList = [];
      }
      if (!res.packageFileList) {
        res.packageFileList = [];
      }
      res.countryId = res.buyCountryId;
      res.provinceId = res.buyProvinceId;
      res.cityId = res.buyCityId;
      for (const key in res) {
        formData.data[key] = res[key];
      }
      proxy
        .post("/fileInfo/getList", {
          businessIdList: [businessId],
        })
        .then((fileObj) => {
          if (fileObj[businessId] && fileObj[businessId].length > 0) {
            formData.data.fileList = fileObj[businessId]
              .filter((x) => x.businessType === "1")
              .map((x) => ({ raw: x, name: x.fileName, url: x.fileUrl }));
            formData.data.packageFileList = fileObj[businessId]
              .filter((x) => x.businessType === "2")
              .map((x) => ({ raw: x, name: x.fileName, url: x.fileUrl }));
          }
        });
      if (
        formData.data.contractProductList &&
        formData.data.contractProductList.length > 0
      ) {
        for (let i = 0; i < formData.data.contractProductList.length; i++) {
          const e = formData.data.contractProductList[i];
          e.rowId = uuidv4();
          if (e.ehsdJson) {
            let obj = JSON.parse(e.ehsdJson);
            e.packMethod = obj.packMethod;
            e.tradeMethods = obj.tradeMethods;
          }
          if (route.query.processType == 30) {
            formData.data.contractWaitShipmentList.push({
              productCode: e.productCode,
              rowId: e.rowId,
              productId: e.productId,
              productName: e.productName,
              quantity: null,
              waitQuantity: e.quantity,
            });
          }
        }
        if (route.query.processType == 30) {
          formData.data.contractShipmentList = [];
          changeWaitQuantity();
        }
        let ids = formData.data.contractProductList.map((x) => x.productId);
        proxy
          .post("/fileInfo/getList", {
            businessIdList: ids,
          })
          .then((fileObj) => {
            for (let i = 0; i < formData.data.contractProductList.length; i++) {
              const e = formData.data.contractProductList[i];
              for (const key in fileObj) {
                if (e.productId === key) {
                  e.fileList = fileObj[key] || [];
                  if (e.fileList && e.fileList.length > 0) {
                    e.fileUrl = e.fileList[0].fileUrl;
                  }
                }
              }
            }
          });
        changeProductPrice();
      }
      if (formData.data.countryId) {
        getCityData(formData.data.countryId, "20");
      }
      if (formData.data.provinceId) {
        getCityData(formData.data.provinceId, "30");
      }
    });
  } else if (
    route.query &&
    route.query.businessId &&
    !route.query.processType
  ) {
    let businessId = route.query.businessId;
    proxy.post("/contract/detail", { id: businessId }).then((res) => {
      // if (res && res.dataJson) {
      //   res = { ...res, ...JSON.parse(res.dataJson) };
      // }
      if (res && res.buyCorporationName) {
        proxy
          .post("/customer/selPage", {
            keyword: res.buyCorporationName,
            userId: userInfo.user.userId,
          })
          .then((res) => {
            customerList.value = res.rows.map((x) => ({
              ...x,
              label: x.name,
              value: x.id,
            }));
          });
      }
      if (!res.fileList) {
        res.fileList = [];
      }
      if (!res.packageFileList) {
        res.packageFileList = [];
      }
      res.countryId = res.buyCountryId;
      res.provinceId = res.buyProvinceId;
      res.cityId = res.buyCityId;
      for (const key in res) {
        formData.data[key] = res[key];
      }
      formData.data.oldContractId = formData.data.id;
      delete formData.data.id;
      delete formData.data.code;
      proxy
        .post("/fileInfo/getList", {
          businessIdList: [businessId],
        })
        .then((fileObj) => {
          if (fileObj[businessId] && fileObj[businessId].length > 0) {
            formData.data.fileList = fileObj[businessId]
              .filter((x) => x.businessType === "1")
              .map((x) => ({ raw: x, name: x.fileName, url: x.fileUrl }));
            formData.data.packageFileList = fileObj[businessId]
              .filter((x) => x.businessType === "2")
              .map((x) => ({ raw: x, name: x.fileName, url: x.fileUrl }));
          }
        });
      if (
        formData.data.contractProductList &&
        formData.data.contractProductList.length > 0
      ) {
        for (let i = 0; i < formData.data.contractProductList.length; i++) {
          const e = formData.data.contractProductList[i];
          e.rowId = uuidv4();
          if (e.ehsdJson) {
            let obj = JSON.parse(e.ehsdJson);
            e.packMethod = obj.packMethod;
            e.tradeMethods = obj.tradeMethods;
          }
        }
        formData.data.contractShipmentList = [];
        if (
          (formData.data.contractWaitShipmentList &&
            formData.data.contractWaitShipmentList.length == 0) ||
          formData.data.contractWaitShipmentList == undefined
        ) {
          formData.data.contractWaitShipmentList = [];
          for (let i = 0; i < formData.data.contractProductList.length; i++) {
            const e = formData.data.contractProductList[i];
            formData.data.contractWaitShipmentList.push({
              productCode: e.productCode,
              rowId: e.rowId,
              productId: e.productId,
              productName: e.productName,
              quantity: null,
              waitQuantity: e.quantity,
            });
          }
          changeWaitQuantity();
        }

        // 变更之前老产品数据
        formData.data.oldContractProductList = proxy.deepClone(
          formData.data.contractProductList
        );
        let ids = formData.data.contractProductList.map((x) => x.productId);
        proxy
          .post("/fileInfo/getList", {
            businessIdList: ids,
          })
          .then((fileObj) => {
            for (let i = 0; i < formData.data.contractProductList.length; i++) {
              const e = formData.data.contractProductList[i];
              for (const key in fileObj) {
                if (e.productId === key) {
                  e.fileList = fileObj[key] || [];
                  if (e.fileList && e.fileList.length > 0) {
                    e.fileUrl = e.fileList[0].fileUrl;
                  }
                }
              }
            }
          });
        changeProductPrice();
      }
      // if (
      //   formData.data.contractProjectList &&
      //   formData.data.contractProjectList.length > 0
      // ) {
      //   formData.data.contractProjectList =
      //     formData.data.contractProjectList.map((x) => {
      //       delete x.id;
      //       return x;
      //     });
      // }
      // if (
      //   formData.data.contractShipmentList &&
      //   formData.data.contractShipmentList.length > 0
      // ) {
      //   formData.data.contractShipmentList =
      //     formData.data.contractShipmentList.map((x) => {
      //       delete x.id;
      //       return x;
      //     });
      // }
      if (formData.data.countryId) {
        getCityData(formData.data.countryId, "20");
      }
      if (formData.data.provinceId) {
        getCityData(formData.data.provinceId, "30");
      }
    });
  }
});

const checkShow = () => {
  if (
    userInfo.roles.includes("purchasingOfficer") &&
    route.query.flowKey == "contract_update_flow" &&
    route.query.processType
  ) {
    showAllData.value = false;
  }
};

const selectShipmentData = ref([]);
const tableDom = ref(null);
const handleSelectionChange = (data) => {
  selectShipmentData.value = data;
};
const handleAddShipment = () => {
  if (formData.data.shipmentTime) {
    if (selectShipmentData.value && selectShipmentData.value.length > 0) {
      // 校验
      for (let i = 0; i < selectShipmentData.value.length; i++) {
        const e = selectShipmentData.value[i];
        if (!Number(e.quantity)) {
          return ElMessage("请输入出货数量");
        }
        if (Number(e.quantity) > Number(e.waitQuantity)) {
          return ElMessage(`${e.productName} 出货数量不能超过剩余数量`);
        }
      }
      // push
      for (let i = 0; i < selectShipmentData.value.length; i++) {
        const e = selectShipmentData.value[i];
        formData.data.contractShipmentList.push({
          rowId: e.rowId,
          productId: e.productId,
          productCode: e.productCode,
          productName: e.productName,
          quantity: e.quantity,
          shipmentTime: formData.data.shipmentTime,
        });
        e.quantity = 0;
      }
      // 清空选择的数据
      tableDom.value.clearSelection();
      formData.data.shipmentTime = "";
      changeWaitQuantity();
    } else {
      ElMessage("请勾选数据");
    }
  } else {
    ElMessage("请选择出货日期");
  }
};
const changeWaitQuantity = () => {
  for (let i = 0; i < formData.data.contractProductList.length; i++) {
    if (formData.data.contractProductList[i].quantity) {
      formData.data.contractWaitShipmentList[i].waitQuantity =
        formData.data.contractProductList[i].quantity;
    }
  }
  if (
    formData.data.contractShipmentList &&
    formData.data.contractShipmentList.length > 0
  ) {
    for (let i = 0; i < formData.data.contractWaitShipmentList.length; i++) {
      const e = formData.data.contractWaitShipmentList[i];
      let arr = formData.data.contractShipmentList.filter(
        (x) => x.rowId === e.rowId
      );
      let quantity = 0;
      for (let j = 0; j < arr.length; j++) {
        quantity += arr[j].quantity;
      }
      e.waitQuantity = e.waitQuantity - quantity;
    }
  }
};
const flitterData = (arr) => {
  let spanOneArr = [];
  let concatOne = 0;
  arr.forEach((item, index) => {
    if (index === 0) {
      spanOneArr.push(1);
    } else {
      //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
      if (item.shipmentTime === arr[index - 1].shipmentTime) {
        //第一列需合并相同内容的判断条件
        spanOneArr[concatOne] += 1;
        spanOneArr.push(0);
      } else {
        spanOneArr.push(1);
        concatOne = index;
      }
    }
  });
  return {
    one: spanOneArr,
  };
};

const objectSpanMethod = ({ rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    const _row = flitterData(formData.data.contractShipmentList).one[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
.img {
  object-fit: contain;
  width: 16px;
  height: 16px;
  vertical-align: middle;
}

.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
.shrinkPadding {
  padding-right: 0 !important;
}
.hideCollapse {
  margin-top: -62px;
  border: 0 !important;
}
::v-deep(.el-collapse-item__arrow) {
  display: none !important;
}
::v-deep(.el-collapse-item__wrap) {
  border: 0 !important;
}
::v-deep(.el-collapse-item__header) {
  border: 0 !important;
}
</style>
