<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules"  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="CK" :disabled="!!form.id"></bill-number-input>
<!--            <el-input v-model="form.billNumber" placeholder="请输入单据编号" />-->
          </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-row>
        <el-col :span="8">
          <el-form-item label="出库类型" prop="outType">
            <el-select filterable v-model="form.outType" placeholder="请输入出库类型" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.sys_out_type" :key="dict.value" :label="dict.label"
                         :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="船舶名称" prop="vesselName">
            <el-select v-model="form.vesselId" filterable placeholder="请输入船舶名称" style="width: 100%" clearable
                       @change="setVesselDetail">
              <el-option v-for="item in vesselList" :key="item.id" :label="item.vesselName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="航次号" prop="voyageNo">
            <el-input v-model="form.voyageNo" placeholder="请输入航次号" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="stock-content">
      <div v-if="!tableReadonly">
        <el-button type="primary" plain @click="addStockOut">添加出库单</el-button>
        <el-button type="danger" plain @click="deleteStocks">删除选中项</el-button>
      </div>
      <el-form ref="listForm" style="flex: 1;margin-top: 10px;" :model="form" v-enterboard>
        <el-table v-if="!loading" highlight-current-row ref="table" style="height: 100%;" height="62vh" :data="form.ckBillCargos" :summary-method="getSummaries"
          show-summary @selection-change="selectionChange" border stripe>
          <el-table-column v-bind="tableIndexAttrs" align="center" />
          <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="电子账册项号"> <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="规格类型品质">{{ scope.row.cargoSpec }}</el-descriptions-item>
                <el-descriptions-item label="原产国"><dict-tag :options="dict.type.sys_origin_country" :value="scope.row.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="billNumber">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.outBillNumber }}</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">
              <el-form-item prop="cargoNum" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoNum }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoNum"
                  :min="0" :max="getMaxData(scope.row).cargoNum" :precision="2" placeholder="输入件数" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="cargoWt">
            <template slot-scope="scope">
              <el-form-item class="margin-none" :prop="'ckBillCargos.' + scope.$index + '.cargoWt'"
                :rules="rules.cargoWt">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoWt }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoWt" :min="0"
                  :precision="2" :max="getMaxData(scope.row).cargoWt" placeholder="输入重量" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="体积" prop="cargoVol">
            <template slot-scope="scope">
              <el-form-item prop="cargoVol" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoVol }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoVol"
                  :min="0" :precision="2" :max="getMaxData(scope.row).cargoVol" placeholder="输入体积" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice">
            <template slot-scope="scope">
              <el-form-item prop="unitPrice" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.unitPrice }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.unitPrice"
                                 :min="0" :precision="4"  placeholder="输入单价" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="cargoValue">
            <template slot-scope="scope">
              <el-form-item prop="cargoValue" class="margin-none">
                <div   v-if="tableReadonly"  class="nomal-text">{{ scope.row.cargoValue }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoValue"
                :min="0" :precision="4" 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 style="height: 60vh;" :cust-id="form.custId" :disable-items="form.ckBillCargos" :search-keyword="searchKeyword" @confirm="chooseStock" @cancel="open = false" @updateList="updateStockList"></StockChoose>
    </el-dialog>

  </div>
</template>

<script>
import { listCust } from "@/api/jxc/cust";
import { listCkstock } from "@/api/jxc/ckstock";
import { getCkbillInfo, outBill } from '@/api/jxc/ckbill';
import { delCkcargo, recallOutBill } from '@/api/jxc/ckcargo';
import StockChoose from "../StockChoose";
import { listVessel } from "@/api/jxc/vessel";

export default {
  name: 'StockOut',
  dicts: ['sys_origin_country','sys_out_type'],
  components: {
    StockChoose
  },
  props: {
    // 单据信息
    billInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    // 传人的出库明细
    modifyData: {
      type: Object,
      default() {
        return {};
      }
    },
    readonly: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      vesselList: [],
      open: false,
      loading: false,
      form: {
        ckBillCargos: []
      },
      rules: {
        cargoNumber: [
          { required: true, message: '货物自然序号不能为空', trigger: 'blur' }
        ],
        itemNumber: [
          { required: true, message: '商品料号不能为空', trigger: 'blur' }
        ],
        bookNumber: [
          { required: true, message: '电子账册项号不能为空', trigger: 'blur' }
        ],
        // customsNo: [
        //   { required: true, message: '报关单号不能为空', trigger: 'blur' }
        // ],
        // listNumber: [
        //   { required: true, message: '核注清单号不能为空', trigger: 'blur' }
        // ],
        expiryDate: [
          { required: true, message: '过期时间不能为空', trigger: 'blur' }
        ],
        cargoValue: [
          { required: true, message: '货物价值不能为空', trigger: 'blur' }
        ],
        stockId: [
          { required: true, message: '库场ID不能为空', trigger: 'blur' }
        ],
        billDate: [
          { required: true, message: '单据日期不能为空', trigger: 'blur' }
        ],
        billNumber: [
          { required: true, message: '单据编号不能为空', trigger: 'blur' }
        ],
        custId: [
          { required: true, message: '货主不能为空', trigger: 'blur' }
        ],
        cargoName: [
          { required: true, message: '货物名称不能为空', trigger: 'blur' }
        ],
        billNo: [
          { 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' }
        ]
      },
      // 选中的库存明细
      selectedList: [],
      // 货主
      custList: [],
      // 货物库存列表
      stockList: [],
      // 记录选择的货主ID 用于新增切换货主时提示
      tempCustId: null,
    };
  },
  // watch: {
  //   billInfo() {
  //     this.getDetail();
  //   },
  //   modifyData() {
  //     this.getDetail();
  //   }
  // },
  computed: {
    // 表格内容只读
    tableReadonly() {
      return this.readonly || this.form.billStatus == 1;
    },
    tableIndexAttrs() {
      if (this.tableReadonly) {
        return {
          label: '序号',
          type: 'index',
          width: '50',
        }
      }
      return {
        type: 'selection',
        width: '55',
      }
    }
  },
  created() {
    this.getVesselList();
  },
  methods: {
    // getCargoValue(row){
    //   const value = row.unitPrice * row.cargoWt;
    //   row.cargoValue = isNaN(value) ? 0 : value.toFixed(4);
    //   return row.cargoValue;
    // },
    init() {
      this.getCustList();
      this.getDetail();
    },
    getVesselList() {
      let param = {};
      listVessel(param).then(response => {
        this.vesselList = response.data;
      }).catch(e => {
      });
    },
    setVesselDetail(vesselId) {

      if (!vesselId) {
        this.form.vesselName = '';
        this.form.vesselId = '';
        return;
      }
      this.vesselList.forEach(ele => {
        if (ele.id == vesselId) {
          this.form.vesselName = ele.vesselName;
        }
      });
    },
    getMaxData(row) {
      if (this.stockList.length) {
        const index = this.stockList.findIndex(val => val.stockId === row.outStockId && val.billNumber === row.outBillNumber && val.cargoId === row.cargoId);
        if (index > -1) {
          const item = this.stockList[index];
          return {
            cargoNum: item.cargoNum,
            cargoWt: item.cargoWt,
            cargoValue: item.cargoValue,
            cargoVol: item.cargoVol
          };
        }
      }
      return {
        cargoNum: Infinity,
        cargoWt: Infinity,
        cargoValue: Infinity,
        cargoVol: Infinity
      };
    },
    cancel(e) {
      this.$emit('close', e);
    },
    refreshList() {
      this.$emit('refresh');
    },
    validate(success) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.ckBillCargos.length === 0) {
            this.$message({
              message: '请添加出库明细',
              type: 'warning'
            });
            return;
          }
          this.$refs.listForm.validate((listValid, checkItem) => {
            if (listValid) {
              const tempChoose = {};
              let findRepeat = false;
              let findValueEmpty = false;
              this.form.ckBillCargos.forEach(val => {
                const checkIdef = `${val.outStockId}/${val.outBillNumber}`;
                if (tempChoose[val.cargoId] && tempChoose[val.cargoId] === checkIdef) {
                  findRepeat = true;
                }
                tempChoose[val.cargoId] = checkIdef;
                if (!val.cargoWt && !val.cargoNum && !val.cargoVol) {
                  findValueEmpty = true;
                }
              });
              if (findRepeat) {
                this.$message({
                  message: '出库单重复了，请修改',
                  type: 'warning'
                });
                return;
              }
              if (findValueEmpty) {
                this.$message({
                  message: '货物重量、数量、体积不能同时为空',
                  type: 'warning'
                });
                return;
              }
              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(() => {
        this.form.ckBillCargos.forEach(val => {
          val.custId = this.form.custId;
          val.custName = this.form.custName;
          val.custCode = this.form.custCode;
        });
        const params = { ...this.form };
        // 1入库 2出库
        // params.billType = '2';
        params.submitStatus = submitStatus;
        this.loading = true;
        outBill(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;
          recallOutBill(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);
      });
    },
    addStockOut() {
      if (!this.form.custId) {
        this.$message('请先选择货主');
        return;
      }
      this.open = true;
    },
    // 获取出库明细列表
    getDetail() {
      let billId = this.modifyData.billId || this.billInfo.id || '';
      if (billId) {
        this.loading = true;
        getCkbillInfo(billId).then(res => {
          const data = res.data || {};
          if (!data.ckBillCargos) {
            data.ckBillCargos = [];
          }
          const firstitem = data.ckBillCargos[0];
          if (firstitem) {
            data.custId = firstitem.custId;
            data.custName = firstitem.custName;
            data.custCode = firstitem.custCode;
          }

          this.form = data;

          this.getStockList();
          this.loading = false;
          this.$nextTick(() => {
            if (this.$refs.table) {
              this.$refs.table.doLayout();
            }
          });
        }).catch(e => {
          this.loading = false;
        });
      }

    },
    // 更新库存列表
    updateStockList(list) {
      this.stockList = list;
    },
    // 获取仓库库存列表
    getStockList() {
      if (!this.form.custId) {
        return;
      }
      listCkstock({
        custId: this.form.custId,
      }).then(res => {
        this.stockList = res.data || [];
      }).catch(e => {
      });
    },
    // 选择了货物库存
    chooseStock(list) {
      const noIdItems = list.map(val => {
        // 这里要确认接受什么参数
        return {
          ...val,
          outBillNumber: val.billNumber,
          outStockId: val.stockId,
          billNumber: null,
          stockId: null,
          id: null,
        };
      });
      this.open = false;
      this.form.ckBillCargos.splice(0, 0, ...noIdItems);
      this.$refs.table.bodyWrapper.scrollTop = this.$refs.table.bodyWrapper.scrollHeight;
      this.$nextTick(() => {
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.$refs.table.doLayout();
      });

    },
    // 设置客户货主
    setCustDetail(custId) {
      console.log(custId);
      console.log(this.tempCustId);
      if (this.form.ckBillCargos.length && 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.ckBillCargos = [];
          this.selectedList = [];
          this.$refs.table.clearSelection();
        }).catch(() => {
          this.form.custId = this.tempCustId;
        });
      } else {
        this.tempCustId = custId;
      }

    },
    // 获取客户货主
    getCustList() {
      listCust({}).then(response => {
        this.custList = response.data;
      }).catch(e => {
      });
    },
    // 选中库存明细
    selectionChange(sel) {
      this.selectedList = sel;
    },
    // 删除明细
    deleteStocks() {
      if (this.selectedList.length) {
        this.$confirm('删除的信息将无法找回，确定删除吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const serveIds = this.selectedList.filter(val => val.id).map(val => val.id).join();
          const didDelete = () => {
            this.form.ckBillCargos = this.form.ckBillCargos.filter(val => !this.selectedList.includes(val));
            this.selectedList = [];
            this.$refs.table.clearSelection();
          }
          if (serveIds) {
            // 删除
            this.loading = true;
            delCkcargo(serveIds).then(res => {
              didDelete();
              this.loading = false;
              this.refreshList();
            }).catch(e => {
              this.loading = false;
            })
          } else {
            didDelete();
          }

        }).catch((action) => {

        });
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index < 5) {
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          // sums[index] += ' 元';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    }
  },
}
</script>

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

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

.stock-content {
  display: flex;
  flex-direction: column;
  height: 70vh;
}

.nomal-text {
  padding: 4px 5px;
}

.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>
