<template>
  <div class="s-page">
    <el-page-header @back="goBack" :content="title"></el-page-header>
    <el-divider></el-divider>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>单据信息</span>
      </div>
      <div class="mymain-container">
        <el-form ref="formData" :rules="rules" :model="formData" label-width="110px" size="small" label-position="left">
          <el-row :gutter="20" justify="start">
            <el-col :span="8" v-if="id">
              <el-form-item label="单据状态">
                <el-input
                  type="text"
                  :value="
                    formData.flag == 'SAVE'
                      ? '保存'
                      : formData.flag == 'SUBMIT'
                      ? '已提交'
                      : formData.flag == 'OK'
                      ? '确认收货'
                      : ''
                  "
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="id">
              <el-form-item label="单据编号">
                <el-input type="text" :value="formData.partsRetId" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="网点名称" prop="websitId" :required="true">
                <el-select
                  v-model="formData.websit"
                  disabled
                  value-key="websitId"
                  @change="changeWebsit"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in websitList"
                    :key="item.websitId"
                    :label="`(${item.websitId})${item.name}`"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="购买方" :required="true" style="padding-bottom: 1px">
                <el-radio-group v-model="formData.buyPeople">
                  <el-radio disabled label="WORKER">内部师傅</el-radio>
                  <el-radio disabled label="CUSTOMER">客户</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <template v-if="formData.buyPeople == 'CUSTOMER'">
              <el-col :span="8">
                <el-form-item label="客户姓名" prop="workerName" :required="true">
                  <el-input type="text" disabled v-model="formData.workerName" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户联系电话" prop="workerMobile" :required="true">
                  <el-input type="text" disabled v-model="formData.workerMobile" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
            </template>
            <template v-else>
              <el-col :span="8">
                <el-form-item label="师傅姓名" prop="worker" :required="true">
                  <el-input type="text" v-model="formData.workerName" disabled placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
								<el-form-item label="师傅身份证" prop="identity" :required="true">
									<el-input type="text" v-model="formData.identity" :disabled="formType == 2" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col> -->
              <el-col :span="8">
                <el-form-item label="师傅联系电话" prop="workerMobile" :required="true">
                  <el-input type="text" v-model="formData.workerMobile" disabled placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="8">
              <el-form-item label="销售类型" :required="true" style="padding-bottom: 1px">
                <el-radio-group v-model="formData.salesType">
                  <el-radio disabled label="零售">零售</el-radio>
                  <el-radio disabled label="工程">工程</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="销售订单号" :required="true">
                <el-input
                  type="text"
                  v-model="formData.salesId"
                  @change="getDetail"
                  disabled
                  placeholder="请输入销售订单号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-button
                v-if="formType != 2"
                size="small"
                type="primary"
                @click="
                  isShowNo = true
                  getOrderList()
                "
                >选择</el-button
              >
            </el-col>
            <el-col :span="5">
              <el-form-item label="销售金额">
                <el-input type="text" :value="formData.totalAmount" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="时间">
                <el-input type="text" :value="formData.payTime" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="入库仓库" prop="storage">
                <el-select
                  v-model="formData.storage"
                  value-key="storageId"
                  :disabled="true"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in warehouseList"
                    :key="index"
                    :label="item.storageName"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="formData.salesType == '工程'">
              <el-col :span="6">
                <el-form-item label="工程名称" :required="true">
                  <el-input type="text" :value="formData.projectName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工程编号" :required="true">
                  <el-input type="text" :disabled="true" v-model="formData.projectNo" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="负责人" :required="true">
                  <el-input type="text" :disabled="true" v-model="formData.manger" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" :required="true">
                  <el-input type="text" :disabled="true" v-model="formData.mobile" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目时间" :required="true">
                  <el-date-picker
                    style="width: 50%"
                    v-model="formData.startTime"
                    type="date"
                    :disabled="true"
                    value-format="yyyy-MM-dd"
                    placeholder="开始日期"
                  >
                  </el-date-picker>
                  <el-date-picker
                    style="width: 50%"
                    v-model="formData.endTime"
                    type="date"
                    :disabled="true"
                    value-format="yyyy-MM-dd"
                    placeholder="结束日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目地址" prop="province" :required="true">
                  <el-row>
                    <el-col :span="5" style="margin-right: 12px">
                      <el-input type="text" v-model="formData.province" disabled placeholder="请选择省"></el-input>
                    </el-col>
                    <el-col :span="5" style="margin-right: 12px">
                      <el-input type="text" v-model="formData.city" disabled placeholder="请选择市"></el-input>
                    </el-col>
                    <el-col :span="5" style="margin-right: 12px">
                      <el-input type="text" v-model="formData.area" disabled placeholder="请选择区"></el-input>
                    </el-col>
                    <el-col :span="8">
                      <el-input type="text" v-model="formData.street" disabled placeholder="请选择街道"></el-input>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="" prop="address">
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-input
                        type="text"
                        v-model="formData.address"
                        :disabled="true"
                        placeholder="详细地址"
                      ></el-input>
                    </el-col>
                    <!-- <el-col :span="2">
											<geographicalPosi :disabled="formType==2" :formData="this.formData" @selectPosi="selectAddress"/>
										</el-col> -->
                  </el-row>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="6" v-if="id">
              <el-form-item label="制单人">
                <el-input type="text" :value="formData.createBy" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="id">
              <el-form-item label="制单时间">
                <el-input type="text" :value="formData.createTime" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="id">
              <el-form-item label="审核人">
                <el-input type="text" :value="formData.confirmBy" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="id">
              <el-form-item label="审核时间">
                <el-input type="text" :value="formData.confirmTime" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件">
                <ImageUpload :fileList="formData.fileUrl" :limit="1" :isEdit="formType !== 2" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="formData.remark"
                  :disabled="formType == 2"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>配件信息</span>
      </div>
      <!-- <el-button size="small" type="primary" @click="add()">添加</el-button> -->
      <label>使用类型: </label>
      <el-radio-group v-model="formData.orderUseType">
        <el-radio :disabled="formType == 2" label="INSIDE">保内</el-radio>
        <el-radio :disabled="formType == 2" label="OUT">保外</el-radio>
      </el-radio-group>
      <div class="table">
        <el-table :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column label="配件名称" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.goods"
                @change="changeGoods"
                value-key="goodsId"
                :disabled="true"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in scope.row.goodsList"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="goods.goodsSalesUnit" align="center" label="单位"></el-table-column>
          <el-table-column prop="" align="center" label="数量">
            <template slot-scope="scope">
              <el-input
                type="number"
                v-model="scope.row.oldRefundQty"
                :disabled="isEdit != scope.$index || formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="goods.goodsCode" align="center" label="配件编码"></el-table-column>
          <el-table-column prop="goods.brandRelaName" align="center" label="适用品牌"></el-table-column>
          <el-table-column prop="goods.productRelaName" align="center" label="适用产品大类"></el-table-column>
          <el-table-column prop="goods.price" align="center" label="销售价格"></el-table-column>
          <el-table-column prop="goods.saleAmount" align="center" label="销售金额">
            <!-- <template slot-scope="scope" v-if="scope.row.oldRefundQty && scope.row.goods && scope.row.goods.price">
              {{ (scope.row.goods.price * 100 * scope.row.oldRefundQty) / 100 }}
            </template> -->
          </el-table-column>
          <!-- <el-table-column prop="goods.qty" align="center" label="库存数量"></el-table-column> -->
          <el-table-column prop="" align="center" label="退款金额" v-if="formData.orderUseType == 'INSIDE'">
            <template slot-scope="scope">
              <el-input
                type="number"
                v-model="scope.row.refundAmount"
                :disabled="isEdit != scope.$index || formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="140">
            <template slot-scope="scope" v-if="formType != 2">
              <el-button size="mini" type="primary" v-if="scope.$index != isEdit" @click="isEdit = scope.$index"
                >编辑</el-button
              >
              <el-button size="mini" type="danger" @click="dataList.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>旧件信息</span>
      </div>
      <el-button v-if="formType != 2" size="small" type="primary" @click="add()">添加</el-button>
      <div class="table">
        <el-table :data="oldList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column label="工单号" align="center">
            <template slot-scope="scope">
              <el-input
                type="text"
                v-model="scope.row.orderId"
                :disabled="formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="工单品牌" align="center">
            <template slot-scope="scope">
              <el-input
                type="text"
                v-model="scope.row.orderBrand"
                :disabled="formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="用户姓名" align="center">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.name" :disabled="formType == 2" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="用户电话" align="center">
            <template slot-scope="scope">
              <el-input
                type="number"
                v-model="scope.row.phone"
                :disabled="formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="配件名称" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.partsName" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column> -->
          <el-table-column label="配件名称" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.goods"
                @change="
                  val => {
                    changeGoods1(val, scope.row)
                  }
                "
                value-key="goodsId"
                :disabled="formType == 2"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in scope.row.goodsList"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="配件编码" align="center">
            <template slot-scope="scope">
              <el-input
                type="text"
                v-model="scope.row.partsCode"
                :disabled="formType == 2"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.unit" :disabled="formType == 2" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.qty" :disabled="formType == 2" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="140">
            <template slot-scope="scope" v-if="formType != 2">
              <el-button size="mini" type="danger" @click="oldList.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <div class="page-footer">
      <div class="footer">
        <el-button
          v-if="formType == 0 || (formType == 1 && formData.flag == 'SAVE')"
          size="small"
          type="primary"
          @click="save()"
          >保存</el-button
        >
        <el-button v-if="formType != 0 && formData.flag == 'SAVE'" size="small" type="primary" @click="submit()"
          >提交</el-button
        >
        <el-button v-if="formType != 0 && formData.flag == 'SUBMIT'" size="small" type="primary" @click="confirm()"
          >确认收货</el-button
        >
        <el-button size="small" type="info" @click="goBack">返回</el-button>
      </div>
    </div>
    <el-dialog
      title="微信支付"
      :visible.sync="isPay"
      width="50%"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="payCodeUrl = ''"
    >
      <h3>扫二维码支付</h3>
      <el-image :src="$showImgUrl(payCodeUrl)" fit="fit"></el-image>
    </el-dialog>
    <!-- 选择销售订单号 -->
    <el-dialog
      title="选择销售订单"
      :visible.sync="isShowNo"
      width="80%"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="close"
    >
      <el-form ref="formData1" :model="formData1" label-width="110px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="网点名称" prop="websit_id">
              <el-select v-model="formData1.websit_id" @change="changeWebsit" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in websitList"
                  :key="item.websitId"
                  :label="`(${item.websitId})${item.name}`"
                  :value="item.websitId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="师傅姓名" prop="worker_name">
              <el-select v-model="formData1.worker_name" filterable placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in workerList.filter(item => {
                    return !formData1.websit_id || item.websitId == formData1.websit_id
                  })"
                  :key="item.id"
                  :label="item.nickName + '-' + item.mobile"
                  :value="item.nickName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="师傅联系电话" prop="worker_mobile">
              <el-input type="text" v-model="formData1.worker_mobile" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料名称" prop="goods" align="center">
              <el-select
                v-model="formData1.goods"
                filterable
                @focus="
                  () => {
                    if (!this.formData1.websit_id) {
                      return this.$message.warning('请先选择网点名称！')
                    }
                  }
                "
                value-key="goodsId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option v-for="item in goodsList" :key="item.goodsId" :label="item.goodsName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售订单号" prop="sales_id">
              <el-input type="text" v-model="formData1.sales_id" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
						<el-form-item label="规格型号" align="center">
							<el-select v-model="formData1.goods" @focus="()=>{
								if(!this.formData1.websit_id){return this.$message.warning('请先选择网点名称！');}
							}" value-key="goodsId" placeholder="请选择" style="width: 100%;">
							    <el-option
							      v-for="item in goodsList"
							      :key="item.goodsId"
							      :label="item.goodsSpecification"
							      :value="item">
							    </el-option>
							  </el-select>
						</el-form-item>
					</el-col> -->
          <el-col :span="18">
            <el-row type="flex" justify="end">
              <el-col :span="3">
                <el-button size="small" @click="resetScreenForm()">清空</el-button>
                <el-button size="small" type="primary" @click="submitScreenForm()">搜索</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div class="clearfix">
        <span>订单信息</span>
      </div>
      <div class="table">
        <el-table
          ref="treeTable"
          :data="orderList"
          element-loading-text="Loading"
          @select="handleSelectionChange"
          @row-click="handleSelectionChange('', $event)"
          border
          fit
          highlight-current-row
          stripe
          style="max-height: 380px; overflow-y: auto"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="salesId" align="center" label="销售单号" width="140"></el-table-column>
          <el-table-column prop="" align="center" label="单据状态" width="120">已支付,已提货</el-table-column>
          <el-table-column prop="websitName" align="center" label="网点名称" width="140"></el-table-column>
          <el-table-column prop="" align="center" label="购买方">
            <template slot-scope="scope">
              {{ scope.row.buyPeople == 'WORKER' ? '内部师傅' : '客户' }}
            </template>
          </el-table-column>
          <el-table-column prop="workerName" align="center" label="师傅姓名"></el-table-column>
          <el-table-column prop="workerMobile" align="center" label="师傅联系电话" width="120"></el-table-column>
          <el-table-column prop="salesType" align="center" label="销售类型"></el-table-column>
          <el-table-column prop="salesTime" align="center" label="销售日期" width="160"></el-table-column>
          <el-table-column prop="totalAmount" align="center" label="订单金额"></el-table-column>
          <el-table-column prop="" align="center" label="订单来源">
            <template slot-scope="scope">
              {{ scope.row.orderSource == 'ONLINE' ? '在线订单' : '自建订单' }}
            </template>
          </el-table-column>
          <el-table-column prop="payType" align="center" label="支付方式">
            <template slot-scope="scope">
              {{ scope.row.payType == 'CASH' ? '现金' : scope.row.payType == 'WECHAT' ? '微信' : '工程支付' }}
            </template>
          </el-table-column>
          <el-table-column prop="payTime" align="center" label="支付时间" width="160"></el-table-column>
          <el-table-column prop="payNo" align="center" label="支付单号" width="160"></el-table-column>
          <el-table-column prop="createBy" align="center" label="创建人" width="160"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间" width="160"></el-table-column>
          <el-table-column prop="updateBy" align="center" label="审核人" width="160"></el-table-column>
          <el-table-column prop="updateTime" align="center" label="审核时间" width="160"></el-table-column>
        </el-table>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="listTotal"
            ></el-pagination>
          </div>
        </div>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button size="small" @click="isShowNo = false">取 消</el-button>
          <el-button size="small" type="primary" @click="confirmOrder()">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWebsit } from '@/api/customerManagement'
import ImageUpload from '@/components/file-upload'
import { listPageV2, getWorker, getCategory, getGoods, getDetail } from '@/api/auxiliaryFittings/auxiliarySalesOrder'
import { add, edit, getNewDetail, getAttachmentList } from '@/api/auxiliaryFittings/attachmentNewReturn'
import { getGoodsList } from '@/api/auxiliaryFittings/auxiliarySalesReturnOrder'
import { storageListPageV2 } from '@/api/storage.js'
export default {
  components: { ImageUpload },
  props: ['id', 'title', 'formType'],
  data() {
    return {
      dataList: [],
      oldList: [],
      websitList: [],
      workerList: [],
      orderList: [],
      goodsList: [],
      attachmentList: [],
      warehouseList: [],
      mainList: [],
      isPay: false,
      payCodeUrl: '',
      salesDetail: {},
      formData: {
        websit: {},
        websitId: '',
        websitName: '',
        fileUrl: [],
        salesId: '',
        partsRetId: '',
        flag: '',
        createBy: '',
        createTime: '',
        confirmBy: '',
        confirmTime: '',
        worker: {},
        workerName: '',
        workerId: '',
        identity: '',
        workerMobile: '',
        remark: '',
        totalAmount: '',
        orderUseType: 'INSIDE',
        salesType: '零售',
        province: '',
        provinceId: '',
        city: '',
        cityId: '',
        area: '',
        areaId: '',
        street: '',
        streetId: '',
        address: '',
        lat: '',
        lng: '',
        orderEnginBaseId: '',
        storage: null,
        storageId: '',
        storageName: ''
      },
      formData1: {
        websit_id: '',
        worker_name: '',
        worker_mobile: '',
        sales_id: '',
        goods: {},
        goodsName: '',
        goodsSpecification: ''
      },
      isEdit: 0,
      companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
      rules: {
        websitId: [{ required: true, message: '请选择网点', trigger: 'change' }],
        worker: [{ required: true, message: '请选择师傅', trigger: 'change' }],
        identity: [
          { required: true, message: '请输入师傅身份证', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
        ],
        workerMobile: [
          { required: true, message: '请输入师傅联系电话', trigger: 'blur' },
          { pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }
        ]
      },
      isShowNo: false,
      pageNum: 1,
      pageSize: 10,
      listTotal: 0
    }
  },
  computed: {},
  created() {
    if (this.id) {
      this.getNewDetail()
    }
    this.getWebsit()
  },
  methods: {
    // 返回
    goBack() {
      this.$emit('back')
    },
    async getDetail(salesId) {
      const that = this
      getDetail({ salesId }).then(async res => {
        Object.assign(this.formData, res.data, {
          websit: { websitId: res.data.websitId, name: res.data.websitName },
          worker: { nickName: res.data.workerName, userId: res.data.workerId },
          fileUrl: res.data?.fileUrl ? res.data?.fileUrl?.split(',').map(item => ({ url: item })) : [],
          storage: {
            storageId: res.data.storageId
          }
        })
        this.getWorker()
        this.getWarehouseList(res.data.websitId)
        for (var item of res.data.items) {
          var ress = await that.getGoods(item.goodsName, 1)
          item.goods = { ...ress.data, price: item.price, saleAmount: item.saleAmount, oldPrice: ress.data.price }
          item.goodsList = ress.data
            ? [{ ...ress.data, price: item.price, saleAmount: item.saleAmount, oldPrice: ress.data.price }]
            : []
          item.oldRefundQty = 1
          item.refundAmount = 0
        }
        this.dataList = res.data.items
      })
    },
    async getNewDetail() {
      const that = this
      getNewDetail({ id: this.id }).then(async res => {
        Object.assign(this.formData, res.data, {
          websit: { websitId: res.data.websitId, name: res.data.websitName },
          worker: { nickName: res.data.workerName, userId: res.data.workerId },
          fileUrl: res.data?.fileUrl ? res.data?.fileUrl?.split(',').map(item => ({ url: item })) : [],
          storage: {
            storageId: res.data.storageId
          }
        })
        this.getWorker()
        this.getWarehouseList(res.data.websitId)
        for (var item of res.data.websitPartsRetItemList) {
          var ress = await that.getGoods(item.goodsName, 1)
          item.goods = { ...ress.data, price: item.price, saleAmount: item.saleAmount, oldPrice: ress.data.price }
          item.goodsList = ress.data
            ? [{ ...ress.data, price: item.price, saleAmount: item.saleAmount, oldPrice: ress.data.price }]
            : []
        }
        var ress = await that.getAttachmentList(res.data.websitId)
        for (var item of res.data.websitPartsRetOldRecordList) {
          item.goods = { goodsId: item.goodsId }
          item.goodsList = ress.data ? ress.data : []
        }
        this.dataList = res.data.websitPartsRetItemList
        this.oldList = res.data.websitPartsRetOldRecordList
      })
    },
    getWebsit() {
      getWebsit({ type: 'C' }).then(res => {
        this.websitList = res.data
      })
    },
    getWarehouseList(websitId) {
      if (!websitId) {
        return (this.warehouseList = [])
      }
      storageListPageV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'a.type', compare: 'like', value: '配件' },
          { param: 'a.status', compare: '=', value: 'true' },
          { param: 'a.websit_id', compare: '=', value: websitId }
        ]
      }).then(res => {
        this.warehouseList = res.data.records
      })
    },
    close() {
      this.$refs.formData1.resetFields()
    },
    confirmOrder() {
      this.isShowNo = false
      this.getDetail(this.selectedRow.salesId)
    },
    getOrderList() {
      listPageV2({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        params: [
          { param: 'a.sales_id', compare: '=', value: this.formData1.sales_id },
          { param: 'a.flag', compare: '=', value: 'PAY_TAKE' },
          { param: 'a.goods_type', compare: '=', value: 'P' },
          { param: 'a.websit_id', compare: '=', value: this.formData1.websit_id },
          { param: 'a.worker_name', compare: '=', value: this.formData1.worker_name },
          { param: 'a.worker_mobile', compare: '=', value: this.formData1.worker_mobile }
        ],
        goodsName: this.formData1.goods.goodsName,
        goodsSpecification: this.formData1.goods.goodsSpecification,
        isFilter: true
      }).then(res => {
        this.orderList = res.data.records
        this.listTotal = res.data.total
      })
    },
    getGoodsList() {
      getGoodsList({
        type: 'P',
        websitId: this.formData1.websit_id
      }).then(res => {
        this.goodsList = res.data
      })
    },
    handleSelectionChange(selection, row) {
      this.$refs.treeTable.clearSelection() // 这里因为需求做的是必选一个，如有其他需求可做调整
      this.$refs.treeTable.toggleRowSelection(row, true)
      this.selectedRow = row
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNum = 1
      this.getOrderList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.pageNum = val
      this.getOrderList()
    },
    // 提交筛选表单
    submitScreenForm() {
      this.pageNum = 1
      this.getOrderList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.formData1.resetFields()
      this.pageNum = 1
      this.getOrderList()
    },
    changeWebsit(e) {
      // this.formData.websitId = e.websitId
      // this.formData.websitName = e.name
      this.getWorker()
      this.getGoodsList()
      this.formData1.worker_name = ''
      this.formData1.goods = {}
      // this.getCategory(e.websitId)
    },
    async getGoods(goodsName, type) {
      const that = this
      if (type == 1) {
        return new Promise((resolve, reject) => {
          getGoods({
            websitId: this.formData.websitId,
            type: 'P',
            goodsName: goodsName,
            orderEnginBaseId: this.formData.orderEnginBaseId,
            saleType: this.formData.salesType,
            storageId: this.formData.storageId
          }).then(res => {
            resolve({
              data: res.data[0]
            })
          })
        })
      } else {
        getGoods({
          websitId: this.formData.websitId,
          type: 'P',
          orderEnginBaseId: this.formData.orderEnginBaseId,
          saleType: this.formData.salesType,
          storageId: this.formData.storageId
        }).then(res => {
          that.dataList[that.isEdit].goodsList = res.data
          console.log(this.dataList)
        })
      }
    },
    getWorker() {
      getWorker({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'b.websit_id', compare: '=', value: this.formData.websitId }]
      }).then(res => {
        this.workerList = res.data.records
      })
    },
    changeWorker(e) {
      this.formData.identity = e.idCard
      this.formData.workerMobile = e.mobile
      this.formData.workerId = e.userId
      this.formData.workerName = e.nickName
    },
    workerBlur(e) {
      this.formData.worker = e.target.value
      this.$forceUpdate()
    },
    changeGoods(e) {
      console.log(e)
      this.dataList[this.isEdit].goodsId = e.goodsId
      this.dataList[this.isEdit].goodsName = e.goodsName
      this.dataList[this.isEdit].goodsSalesUnit = e.goodsSalesUnit
      this.dataList[this.isEdit].brandRelaName = e.brandRelaName
      this.dataList[this.isEdit].productRelaName = e.productRelaName
      this.dataList[this.isEdit].price = e.price
      this.dataList[this.isEdit].goodsCode = e.goodsCode
      this.dataList[this.isEdit].qty = e.qty
    },
    changeGoods1(e, row) {
      row.goodsId = e.goodsId
      row.goodsName = e.goodsName
      row.unit = e.goodsStockUnit
      row.orderBrand = e.brandRelaName
      row.partsName = e.productRelaName
      row.partsCode = e.goodsCode
      row.qty = e.oldQty
    },
    add() {
      getAttachmentList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'a.websit_id', compare: '=', value: this.formData.websitId }]
      }).then(res => {
        this.oldList.push({
          orderId: '',
          orderBrand: '',
          name: '',
          phone: '',
          partsName: '',
          unit: '',
          qty: '',
          partsCode: '',
          goodsList: res.data.records,
          goods: {},
          goodsId: '',
          goodsName: ''
        })
      })
    },
    async getAttachmentList(websit_id) {
      const that = this
      if (websit_id) {
        return new Promise((resolve, reject) => {
          getAttachmentList({
            pageNum: 1,
            pageSize: -1,
            params: [{ param: 'a.websit_id', compare: '=', value: this.formData.websitId }]
          }).then(res => {
            resolve({
              data: res.data.records
            })
          })
        })
      } else {
        getAttachmentList({
          pageNum: 1,
          pageSize: -1,
          params: [{ param: 'a.websit_id', compare: '=', value: this.formData.websitId }]
        }).then(res => {
          this.oldList[this.isEdit].goodsList = res.data.records
        })
      }
    },
    async checkForm() {
      let is_save = true
      this.dataList.forEach(item => {
        if (!item.oldRefundQty || item.oldRefundQty < 1) {
          this.$message.warning('请输入配件数量并且数量大于0！')
          is_save = false
        } else if ((!item.refundAmount || item.refundAmount <= 0) && this.formData.orderUseType == 'INSIDE') {
          this.$message.warning('请输入配件退货金额并且大于0！')
          is_save = false
        }
      })
      return is_save
    },
    confirm() {
      this.$confirm(`请确定是否确认提货, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        edit({
          flag: 'OK',
          partsRetId: this.formData.partsRetId
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('确认提货成功！')
            this.goBack()
          }
        })
      })
    },
    async submit() {
      console.log(this.oldList)
      let is_save = await this.checkForm()
      if (!is_save) {
        return false
      }
      this.$confirm(`请确定是否提交, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(2)
        edit({
          flag: 'SUBMIT',
          salesId: this.formData.salesId,
          partsRetId: this.formData.partsRetId,
          goodsType: 'P',
          type: 'OLD',
          remark: this.formData.remark,
          websitId: this.formData.websitId,
          websitName: this.formData.websitName,
          workerName: this.formData.workerName,
          workerId: this.formData.workerId,
          identity: this.formData.identity,
          workerMobile: this.formData.workerMobile,
          websitPartsRetItems: this.dataList,
          websitPartsRetOldRecordList: this.oldList,
          orderUseType: this.formData.orderUseType,
          fileUrl: this.formData.fileUrl.map(item => item.url).join(','),
          storageId: this.formData.storageId,
          storageName: this.formData.storageName
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('提交成功！')
            this.goBack()
          }
        })
      })
    },
    async save() {
      let is_save = await this.checkForm()
      console.log(is_save)
      if (!is_save) {
        return false
      }
      this.$refs.formData.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formType == 0) {
            add({
              salesId: this.formData.salesId,
              goodsType: 'P',
              type: 'OLD',
              remark: this.formData.remark,
              websitId: this.formData.websitId,
              websitName: this.formData.websitName,
              workerName: this.formData.workerName,
              workerId: this.formData.workerId,
              identity: this.formData.identity,
              workerMobile: this.formData.workerMobile,
              websitPartsRetItems: this.dataList,
              websitPartsRetOldRecordList: this.oldList,
              orderUseType: this.formData.orderUseType,
              fileUrl: this.formData.fileUrl.map(item => item.url).join(','),
              storageId: this.formData.storageId,
              storageName: this.formData.storageName
            }).then(res => {
              if (res.code == 200) {
                this.$message.success('提交成功！')
                this.goBack()
              }
            })
          } else if (this.formType == 1) {
            edit({
              salesId: this.formData.salesId,
              partsRetId: this.formData.partsRetId,
              goodsType: 'P',
              type: 'OLD',
              remark: this.formData.remark,
              websitId: this.formData.websitId,
              websitName: this.formData.websitName,
              workerName: this.formData.workerName,
              workerId: this.formData.workerId,
              identity: this.formData.identity,
              workerMobile: this.formData.workerMobile,
              websitPartsRetItems: this.dataList,
              websitPartsRetOldRecordList: this.oldList,
              orderUseType: this.formData.orderUseType,
              fileUrl: this.formData.fileUrl.map(item => item.url).join(','),
              storageId: this.formData.storageId,
              storageName: this.formData.storageName
            }).then(res => {
              if (res.code == 200) {
                this.dataList = []
                this.$message.success('提交成功！')
                this.goBack()
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
.s-page {
  padding: 20px;
  background-color: #ffffff;
}
.page-footer {
  height: 70px;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  background: #fff;
  padding: 15px 40px;
  box-sizing: border-box;
  transition: all 0.28s;
  text-align: right;
  box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);

  &.hideSidebar {
    margin-left: 54px;
    width: calc(100vw - 54px);
  }

  &.openSidebar {
    margin-left: 210px;
    width: calc(100vw - 210px);
  }

  .tips {
    font-size: 12px;
    color: red;
    margin-top: 10px;
  }
}
::v-deep .el-table__body-wrapper {
  max-height: 300px !important;
  overflow-y: auto !important;
}
</style>
