<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" :disabled="!!form.id" label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="billNumber">
            <bill-number-input ref="billInput" v-model="form.billNumber" type="ZC"></bill-number-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据时间" prop="billDate">
            <el-date-picker clearable v-model="form.billDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择单据时间" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货主" prop="custId">
            <el-select v-model="form.custId" filterable placeholder="请输入货主名称" style="width: 100%" clearable
              @change="setCustDetail">
              <el-option v-for="item in custList" :key="item.id" :label="item.custName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="stock-content">
      <div style="display: flex;align-items: center;margin-top: 10px;">
        <div class="trans-title">转出库场货物</div>
        <el-button style="margin-left: 20px;" v-if="!tableReadonly" type="primary" plain
          @click="addStockOut">选择转出库场货物</el-button>
      </div>
      <el-form ref="outForm" style="margin-top: 10px;" :model="form" v-enterboard>
        <el-table v-if="!loading" highlight-current-row ref="table" :data="form.oldCargo ? [form.oldCargo] : []" border
          stripe>
<!--          <el-table-column type="expand" label="更多">-->
<!--            <template slot-scope="scope">-->
<!--              <el-descriptions class="desc-table" size="mini" :column="5" border>-->
<!--                <el-descriptions-item label="HS编号">{{ scope.row.hsCode }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="自然序号">{{ scope.row.cargoNumber }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="商品料号">{{ scope.row.itemNumber }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="电子账册项号">{{ scope.row.bookNumber }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="报关单号">{{ scope.row.customsNo }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="核注清单号">{{ scope.row.listNumber }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="有效期至">{{ scope.row.expiryDate }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="规格类型品质">{{ scope.row.cargoSpec }}</el-descriptions-item>-->
<!--                <el-descriptions-item label="原产国">{{ scope.row.originCountry }}</el-descriptions-item>-->
<!--              </el-descriptions>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="单据编号" prop="billNumber">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.billNumber }}</div>
            </template>
          </el-table-column>
          <el-table-column label="货物" prop="cargoName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.cargoName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库场仓位" prop="stockName">
            <template slot-scope="scope">
              <div class="nomal-text">
                <WarehouseName :stockCode="scope.row.stockCode" />-{{ scope.row.stockName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="cargoNum">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.nowStockNum }}</div>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="cargoWt">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.nowStockWt }}</div>
            </template>
          </el-table-column>
          <el-table-column label="体积" prop="cargoVol">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.nowStockVol }}</div>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="cargoValue">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.nowCargoValue }}</div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div style="display: flex;align-items: center;margin-top: 20px;">
        <div class="trans-title">转入库场</div>
        <el-button style="margin-left: 20px;" v-if="!tableReadonly" type="success" plain
          @click="addStockTrans">添加转入库场</el-button>
      </div>
      <el-form ref="listInForm" style="flex: 1;margin-top: 10px;" :model="form" v-enterboard >
        <el-table v-if="!loading" highlight-current-row ref="inTable" :data="form.newCargos" show-summary border stripe>
          <el-table-column v-if="!tableReadonly" label="操作" width="80">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="delStockTrans(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column type="expand" label="更多" >
            <template slot-scope="scope">
              <el-descriptions class="desc-table" size="mini" :column="4" border>
                <el-descriptions-item label="HS编号">{{ form.oldCargo.hsCode }}</el-descriptions-item>
                <el-descriptions-item label="自然序号">{{ form.oldCargo.cargoNumber }}</el-descriptions-item>
                <el-descriptions-item label="商品料号">{{ form.oldCargo.itemNumber }}</el-descriptions-item>
                <el-descriptions-item label="电子账册项号"> <el-input v-model="scope.row.bookNumber" placeholder="电子账册项号" /></el-descriptions-item>
                <el-descriptions-item label="报关单号"><el-input v-model="scope.row.customsNo" placeholder="报关单号" /></el-descriptions-item>
                <el-descriptions-item label="核注清单号"><el-input v-model="scope.row.listNumber" placeholder="核注清单号" /></el-descriptions-item>
                <el-descriptions-item label="有效期至"><el-date-picker v-model="scope.row.expiryDate" placeholder="有效期至" type="date" value-format="yyyy-MM-dd" /></el-descriptions-item>
                <el-descriptions-item label="规格类型品质">{{ form.oldCargo.cargoSpec }}</el-descriptions-item>
                <el-descriptions-item label="原产国"><dict-tag :options="dict.type.sys_origin_country" :value="form.oldCargo.originCountry"></dict-tag></el-descriptions-item>
                <el-descriptions-item label="货物流向">
                  <el-select v-model="scope.row.cargoFlow" filterable placeholder="请输入货物流向" style="width: 100%" clearable>
                    <el-option v-for="item in custList" :key="item.id" :label="item.custName" :value="item.custName">
                    </el-option>
                  </el-select>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>
          <el-table-column label="库场" prop="stockName">
            <template slot-scope="scope">
              <div v-if="tableReadonly" class="nomal-text">
                <WarehouseName :stockCode="scope.row.stockCode"></WarehouseName><span>-{{ scope.row.stockName }}</span>
              </div>
              <el-form-item v-else :prop="'newCargos.' + scope.$index + '.stockId'" class="margin-none" :rules="rules.stockId">
                <el-select v-model="scope.row.stockId" filterable placeholder="请输入库场名称" style="width: 100%" clearable
                  @change="setInStockDetail($event, scope.row)">
                  <el-option v-for="item in allStockList" :key="item.id"
                    :label="warehouseName(item) + '-' + item.stockName" :value="item.id">
                    <WarehouseName :stockCode="item.stockCode"></WarehouseName><span>-{{ item.stockName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="cargoNum">
            <template slot-scope="scope">
              <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoNum }}</div>
              <el-form-item v-else :prop="'newCargos.' + scope.$index + '.cargoNum'" class="margin-none" :rules="rules.cargoNum">
                <el-input-number style="width: 100%" controls-position="right" v-model="scope.row.cargoNum" :min="0"
                  :precision="2" placeholder="输入件数" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="cargoWt">
            <template slot-scope="scope">
              <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoWt }}</div>
              <el-form-item v-else class="margin-none" :prop="'newCargos.' + scope.$index + '.cargoWt'" :rules="rules.cargoWt">
                <el-input-number style="width: 100%" controls-position="right" v-model="scope.row.cargoWt" :min="0"
                  :precision="2" placeholder="输入重量" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="体积" prop="cargoVol">
            <template slot-scope="scope">
              <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoVol }}</div>
              <el-form-item v-else :prop="'newCargos.' + scope.$index + '.cargoVol'" class="margin-none" :rules="rules.cargoVol">
                <el-input-number style="width: 100%" controls-position="right" v-model="scope.row.cargoVol" :min="0"
                  :precision="2" placeholder="输入体积" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="cargoValue">
            <template slot-scope="scope">
              <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoValue }}</div>
              <el-form-item v-else :prop="'newCargos.' + scope.$index + '.cargoValue'" class="margin-none" :rules="rules.cargoValue">
                <el-input-number style="width: 100%" controls-position="right" v-model="scope.row.cargoValue" :min="0"
                  :precision="2" placeholder="输入价值" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="stock-btns">
      <el-button v-if="!readonly" type="primary" plain style="margin-right: 20px;"
        @click="confirm">{{ form.billStatus == 1 ? '单据撤销' : '单据确认' }}</el-button>
      <el-button @click="cancel(!readonly)">取消</el-button>
      <el-button v-if="!readonly && form.billStatus != 1" type="primary" @click="save(false)">保存</el-button>
    </div>
    <el-dialog title="选择转场货物" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false"
      destroy-on-close>
      <StockChoose v-if="open" style="height: 70vh;" :cust-id="form.custId" :single="true" :single-item="form.oldCargo"
        @confirm="chooseStock" @cancel="open = false">
      </StockChoose>
    </el-dialog>
  </div>
</template>

<script>
import { listCust } from "@/api/jxc/cust";
import { stockNumList } from '@/api/jxc/ckstock';
import { getTransferInfo, addTransfer, recallTransfer } from '@/api/jxc/ckbill'
import StockChoose from "@/views/jxc/ckoutbound/components/StockChoose";

export default {
  name: 'Transfer',
  dicts: ['sys_origin_country','sys_out_type'],
  components: {
    StockChoose
  },
  props: {
    // 单据信息
    // billInfo: {
    //   type: Object,
    //   default() {
    //     return {};
    //   }
    // },
    // 传人转场单ID
    transferId: {
      type: String | Number,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      open: false,
      loading: false,
      form: {
        billNumber: null,
        custId: null,
        custName: null,
        billDate: null,
        oldCargo: null,
        newCargos: [],
      },
      rules: {
        cargoValue: [
          { required: true, message: '货物价值不能为空', trigger: 'blur' }
        ],
        stockId: [
          { required: true, message: '库场不能为空', trigger: 'change' }
        ],
        billDate: [
          { required: true, message: '单据日期不能为空', trigger: 'blur' }
        ],
        billNumber: [
          { required: true, message: '单据编号不能为空', trigger: 'blur' }
        ],
        custId: [
          { required: true, message: '货主不能为空', trigger: 'blur' }
        ],
        cargoName: [
          { required: true, message: '货物名称不能为空', trigger: 'blur' }
        ],
        cargoWt: [
          { required: true, message: '货物重量不能为空', trigger: 'blur' }
        ],
        cargoNum: [
          { required: true, message: '货物件数不能为空', trigger: 'blur' }
        ],
        cargoVol: [
          { required: true, message: '货物体积不能为空', trigger: 'blur' }
        ],
        stockName: [
          { required: true, message: '库场名称不能为空', trigger: 'blur' }
        ],
        custName: [
          { required: true, message: '货主名称不能为空', trigger: 'blur' }
        ]
      },
      // 货主下所有仓库
      allStockList: [],
      // 货主
      custList: [],
      // 记录选择的货主ID 用于新增切换货主时提示
      tempCustId: null,
    };
  },
  computed: {
    // 表格内容只读
    tableReadonly() {
      return this.readonly || this.form.billStatus == 1;
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getCustList();
      this.getDetail();
      this.getAllStockList();
    },
    cancel(e) {
      this.$emit('close', e);
    },
    refreshList() {
      this.$emit('refresh');
    },
    validate(success) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.newCargos.length === 0) {
            this.$message({
              message: '转出库场不能为空',
              type: 'warning'
            });
            return;
          }
          this.$refs.listInForm.validate((listValid, checkItem) => {
            if (listValid) {
              const tempChoose = {};
              let findRepeat = false;
              let findValueEmpty = false;
              const outNumber = {
                cargoWt: 0,
                cargoNum: 0,
                cargoVol: 0,
                cargoValue: 0,
              }
              this.form.newCargos.forEach(val => {
                if (tempChoose[val.cargoId] && tempChoose[val.cargoId] === val.stockId) {
                  findRepeat = true;
                }
                tempChoose[val.cargoId] = val.stockId;
                if (!val.cargoWt && !val.cargoNum && !val.cargoVol) {
                  findValueEmpty = true;
                }
                outNumber.cargoWt += val.cargoWt;
                outNumber.cargoNum += val.cargoNum;
                outNumber.cargoVol += val.cargoVol;
                outNumber.cargoValue += val.cargoValue;
              });
              // if (findRepeat) {
              //   this.$message({
              //     message: '出库单重复了，请修改',
              //     type: 'warning'
              //   });
              //   return;
              // }
              if (outNumber.cargoNum > this.form.oldCargo.nowStockNum) {
                this.$message({
                  message: '转出件数超出了原库存',
                  type: 'warning'
                });
                return;
              }
              if (outNumber.cargoWt > this.form.oldCargo.nowStockWt) {
                this.$message({
                  message: '转出重量超出了原库存',
                  type: 'warning'
                });
                return;
              }
              if (outNumber.cargoVol > this.form.oldCargo.nowStockVol) {
                this.$message({
                  message: '转出体积超出了原库存',
                  type: 'warning'
                });
                return;
              }
              if (outNumber.cargoValue > this.form.oldCargo.nowCargoValue) {
                this.$message({
                  message: '转出价值超出了原库存',
                  type: 'warning'
                });
                return;
              }
              if (findValueEmpty) {
                this.$message({
                  message: '货物重量、数量、体积不能同时为空',
                  type: 'warning'
                });
                return;
              }
              this.form.oldCargo = {
                ...this.form.oldCargo,
                ...outNumber,
              }
              success();
            } else {
              this.$message({
                message: checkItem[Object.keys(checkItem)[0]][0].message,
                type: 'warning'
              });
            }
          });
        }
      });
    },
    save(submitStatus) {
      if (!this.form.billNumber) {
        this.$refs.billInput.updateNumber().then(res => {
          this.validSendData(submitStatus);
        }).catch(e => {
          this.$message.error('单据编号获取失败');
        });
        return;
      }
      this.validSendData(submitStatus);
    },
    validSendData(submitStatus) {
      this.validate(() => {
        const params = { ...this.form };
        params.submitStatus = submitStatus;
        this.loading = true;
        addTransfer(params).then(res => {
          this.loading = false;
          this.cancel();
          this.refreshList();
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
        }).catch(e => {
          this.loading = false;
        });
      });
    },
    confirm() {
      this.$confirm(`确定${this.form.billStatus == '1' ? '撤销' : '确认'}当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: this.form.billStatus == '1' ? 'warning' : 'info',
      }).then(() => {
        if (this.form.billStatus == '1') {
          // 撤销
          this.loading = true;
          recallTransfer(this.form.id).then(res => {
            this.$message({
              message: '撤销成功！',
              type: 'success'
            });
            this.loading = false;
            this.cancel();
            this.refreshList();
          }).catch(e => {
            this.loading = false;
          });
          return;
        }

        //确认
        this.save(true);
      });
    },
    warehouseName(row) {
      const stock = this.$store.getters.warehouseData[row.stockCode] || {};
      return stock.stockName;
    },
    //仓库
    setInStockDetail(stockId, row) {
      if (stockId == this.form.oldCargo.stockId) {
        row.stockId = row._tempStockId;
        this.$modal.alertError("转入仓库与转出仓库不能相同");
        return;
      }
      row._tempStockId = stockId;
      this.allStockList.forEach(ele => {
        if (ele.id == stockId) {
          row.stockName = ele.stockName;
          row.stockCode = ele.stockCode;
        }
      })
    },
    addStockOut() {
      if (!this.form.custId) {
        this.$message('请先选择货主');
        return;
      }
      this.open = true;
    },
    // 添加转入库场
    addStockTrans() {
      if (!this.form.oldCargo) {
        this.$message('请先选择转出库场货物');
        return;
      }
      this.form.newCargos.push({
        stockId: '',
        stockCode: '',
        stockName: '',
        cargoNum: 0,
        cargoWt: 0,
        cargoVol: 0,
        cargoValue: 0,
        cargoFlow: '',
        expiryDate: '',
        listNumber: '',
        customsNo: '',
        bookNumber: '',
      });
      this.$nextTick(() => {
        this.$refs.inTable.doLayout();
      });
    },
    // 删除转入库场
    delStockTrans(row, index) {
      this.form.newCargos.splice(index, 1);
    },
    // 获取转场详情
    getDetail() {
      if (this.transferId) {
        this.loading = true;
        getTransferInfo(this.transferId).then(res => {
          const data = res.data || {};
          if (!data.newCargos) {
            data.newCargos = [];
          }
          data.newCargos.forEach(item => {
            // 如果item对象中不存在listNumber属性，则为其赋值为空字符串
            if (!item.hasOwnProperty('listNumber')) {
              item.listNumber = '';
            }
            if (!item.hasOwnProperty('customsNo')) {
              item.customsNo = '';
            }
            if (!item.hasOwnProperty('bookNumber')) {
              item.bookNumber = '';
            }
            if (!item.hasOwnProperty('cargoFlow')) {
              item.cargoFlow = '';
            }
            if (!item.hasOwnProperty('expiryDate')) {
              item.expiryDate = '';
            }
          });
          this.form = data;
          this.loading = false;
          this.$nextTick(() => {
            if (this.$refs.table) {
              this.$refs.table.doLayout();
            }
          });
        }).catch(e => {
          this.loading = false;
        });
      }

    },
    // 获取转入库所有仓库
    getAllStockList() {
      let param = {
        // custId: this.form.custId,
      }
      stockNumList(param).then(response => {
        this.allStockList = response.data || [];
      }).catch(e => {
      });
    },
    // 选择了货物库存
    chooseStock(list) {
      const noIdItems = list.map(val => {
        // 这里要确认接受什么参数
        return {
          billNumber: val.billNumber,
          cargoNum: 200,
          cargoValue: 2,
          cargoVol: 0,
          cargoWt: 0,
          nowStockNum: val.cargoNum,
          nowStockVol: val.cargoVol,
          nowStockWt: val.cargoWt,
          nowCargoValue: val.cargoValue,
          cargoId: val.cargoId,
          cargoName: val.cargoName,
          stockId: val.stockId,
          stockCode: val.stockCode,
          stockName: val.stockName,
          hsCode: val.hsCode,
          cargoNumber: val.cargoNumber,
          itemNumber: val.itemNumber,
          bookNumber: val.bookNumber,
          customsNo: val.customsNo,
          listNumber: val.listNumber,
          expiryDate: val.expiryDate,
          cargoSpec: val.cargoSpec,
          originCountry: val.originCountry,
        };
      });
      this.open = false;
      if (noIdItems.length) {
        this.form.oldCargo = noIdItems[0];
      }
    },
    // 设置客户货主
    setCustDetail(custId) {
      if (this.form.oldCargo && this.tempCustId && custId !== this.tempCustId) {
        this.$confirm('切换货主会清空当前转场表单, 是否继续?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          showClose: false,
        }).then(() => {
          this.tempCustId = custId;
          this.custList.forEach(ele => {
            if (ele.id == custId) {
              this.form.custName = ele.custName;
              this.form.custCode = ele.custCode;
            }
          })
          this.form.oldCargo = null;
          this.form.newCargos = [];

        }).catch(() => {
          this.form.custId = this.tempCustId;
        });
      } else {
        this.tempCustId = custId;
      }

    },
    // 获取客户货主
    getCustList() {
      listCust({}).then(response => {
        this.custList = response.data;
      }).catch(e => {
      });
    },
  },
}
</script>

<style scoped>
.stock-btns {
  margin-top: 10px;
  display: flex;
  justify-content: right;
}

::v-deep .el-dialog__body {
  padding-top: 10px;
}

.stock-content {
  display: flex;
  flex-direction: column;
  height: 68vh;
  overflow-y: scroll;
}

.trans-title {
  color: #409EFF;
  font-size: large;
  font-weight: 500;
  line-height: 50px;
}

.nomal-text {
  padding: 8px 10px;
}

.margin-none {
  margin: 0;
}

.desc-table {
  padding: 5px;
}


::v-deep .el-table td.el-table__cell {
  padding: 0;
}

::v-deep .el-table--border .el-table__cell {
  padding: 0;
}

::v-deep .el-table .cell {
  padding: 0;
  text-align: center;
}

::v-deep .el-table--border .el-table__cell:first-child .cell {
  padding-left: 0;
}

::v-deep .el-table th.el-table__cell>.cell {
  padding: 0;
}
</style>
