<template>
  <div class="bill-edit" v-loading="loading">
    <div v-if="loading" style="flex: 1;"></div>
    <el-table v-else ref="table" style="flex: 1;" highlight-current-row height="70vh" :data="form.ckBillCargos" @selection-change="selectionChange"
      border :row-style="rowStyle">
      <!-- <el-table-column v-bind="tableIndexAttrs" align="center" /> -->
      <el-table-column v-if="!tableReadonly" type='selection' width='55'></el-table-column>
      <el-table-column label='序号' type='index' width='50'></el-table-column>
      <el-table-column :label="tableReadonly ? '查看入库信息' : '填写入库信息'" align="center">
        <template slot-scope="scope">
          <el-form :ref="'form' + scope.$index" :model="scope.row" :rules="rules" :show-message="false" v-enterboard>
            <el-descriptions class="desc-table" :column="4" border>
              <el-descriptions-item>
                <template slot="label">货物名称<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoName }}</div>
                <el-form-item v-else prop="cargoId" class="margin-none">
                  <el-select v-model="scope.row.cargoId" filterable placeholder="请输入货物名称或商品序号" style="width: 100%" clearable
                             @change="setCargoDetail($event, scope.row)">
                    <el-option v-for="item in cargoList" :key="item.gdsSeqno" :label="item.cargoName + ' (' + item.gdsSeqno + ')'" :value="item.id" >
                      <span>{{ item.cargoName }} ({{ item.gdsSeqno }})</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">HS编号</template>
                <div class="nomal-text">{{ scope.row.hsCode }}</div>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">仓库名称<rq></rq></template>
                <div class="nomal-text"><WarehouseName :stockCode="scope.row.stockCode"/></div>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">仓位名称<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.stockName }}</div>
                <el-form-item v-else prop="inStockId" class="margin-none">
                  <el-select v-model="scope.row.inStockId" filterable placeholder="请输入仓位名称" style="width: 100%" clearable
                    @change="setStockDetail($event, scope.row)">
                    <el-option v-for="item in stockList" :key="item.id" :label="item.stockName" :value="item.id">
                      <WarehouseName  :stockCode="item.stockCode"></WarehouseName><span>-{{ item.stockName }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">计量单位<rq/></template>
                <div v-if="tableReadonly" class="nomal-text">
                  <dict-tag :options="dict.type.sys_measurement_unit" :value="scope.row.unit"></dict-tag>
                </div>
                <el-form-item v-else prop="unit" class="margin-none">
                  <el-select filterable v-model="scope.row.unit" placeholder="请输入计量单位" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_measurement_unit" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">第一计量单位<rq/></template>
                <div v-if="tableReadonly" class="nomal-text">
                  <dict-tag :options="dict.type.sys_measurement_unit" :value="scope.row.firstUnit"></dict-tag>
                </div>
                <el-form-item v-else prop="firstUnit" class="margin-none">
                  <el-select filterable v-model="scope.row.firstUnit" placeholder="请输入第一计量单位" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_measurement_unit" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物自然序号<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoNumber }}</div>
                <el-form-item v-else prop="cargoNumber" class="margin-none">
                  <el-input v-model="scope.row.cargoNumber" placeholder="请输入货物自然序号" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">商品料号<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.itemNumber }}</div>
                <el-form-item v-else prop="itemNumber" class="margin-none">
                  <el-input v-model="scope.row.itemNumber" placeholder="请输入商品料号" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">电子账册项号<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.bookNumber }}</div>
                <el-form-item v-else prop="bookNumber" class="margin-none">
                  <el-input v-model="scope.row.bookNumber" placeholder="请输入电子账册项号" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">报关单号<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.customsNo }}</div>
                <el-form-item v-else prop="customsNo" class="margin-none">
                  <el-input v-model="scope.row.customsNo" placeholder="请输入报关单号" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">核注清单号<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.listNumber }}</div>
                <el-form-item v-else prop="listNumber" class="margin-none">
                  <el-input v-model="scope.row.listNumber" placeholder="请输入核注清单号" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物件数</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoNum }}</div>
                <el-form-item v-else prop="cargoNum" class="margin-none">
                  <el-input-number v-model="scope.row.cargoNum" placeholder="请输入货物件数" style="width: 100%" :precision="2"
                    :min="0" controls-position="right" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物重量</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoWt }}</div>
                <el-form-item v-else prop="cargoWt" class="margin-none">
                  <el-input-number controls-position="right" v-model="scope.row.cargoWt" :precision="2" :min="0"
                    placeholder="请输入货物重量" style="width: 100%" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物体积(m³)</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoVol }}</div>
                <el-form-item v-else prop="cargoVol" class="margin-none">
                  <el-input-number controls-position="right" v-model="scope.row.cargoVol" :precision="2" :min="0"
                    placeholder="请输入货物体积" style="width: 100%" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物单价</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.unitPrice }}</div>
                <el-form-item v-else prop="unitPrice" class="margin-none">
                  <el-input-number controls-position="right" v-model="scope.row.unitPrice" :precision="4" :min="0"
                                   placeholder="请输入货物单价" style="width: 100%"/>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">货物价值</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoValue }}</div>
                <el-form-item v-else prop="cargoValue" class="margin-none">
                  <el-input-number controls-position="right" v-model="scope.row.cargoValue" :precision="4" :min="0"
                    placeholder="请输入货物价值" style="width: 100%"/>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">币种<rq/></template>
                <div v-if="tableReadonly" class="nomal-text">
                  <dict-tag :options="dict.type.sys_curr_type" :value="scope.row.currType"></dict-tag>
                </div>
                <el-form-item v-else prop="currType" class="margin-none">
                  <el-select filterable v-model="scope.row.currType" placeholder="请输入币种" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_curr_type" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">有效期至<rq></rq></template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.expiryDate }}</div>
                <el-form-item v-else prop="expiryDate" class="margin-none">
                  <el-date-picker clearable v-model="scope.row.expiryDate" style="width: 100%" type="date"
                    value-format="yyyy-MM-dd" placeholder="请选择有效期至">
                  </el-date-picker>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">规格类型品质</template>
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoSpec }}</div>
                <el-form-item v-else prop="cargoSpec" class="margin-none">
                  <el-input v-model="scope.row.cargoSpec" placeholder="请输入规格类型品质" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">原产国<rq/></template>
                <div v-if="tableReadonly" class="nomal-text">
                  <dict-tag :options="dict.type.sys_origin_country" :value="scope.row.originCountry"></dict-tag>
                </div>
                <el-form-item v-else prop="originCountry" class="margin-none">
                  <el-select filterable v-model="scope.row.originCountry" placeholder="请输入原产国" clearable style="width: 100%">
                    <el-option v-for="dict in dict.type.sys_origin_country" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex;align-items: center;">
      <el-form ref="form"  style="flex: 1;margin-top: 25px;" :model="form" :rules="rules"
        label-width="80px" v-enterboard>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="billNumber" >
              <bill-number-input ref="billInput" v-model="form.billNumber" type="RK" :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="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 style="margin-left: 20px;">
        <el-button v-if="!readonly" type="primary" plain
          style="margin-right: 20px;" @click="confirm">{{ form.billStatus == 1 ? '单据撤销' : '单据确认' }}</el-button>
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="!readonly && form.billStatus != 1" type="primary" @click="save(false)">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { listCargo } from "@/api/jxc/cargo";
import { listCust } from "@/api/jxc/cust";
import { listStock } from "@/api/jxc/stock";
import { getCkbillInfo, putBill } from '@/api/jxc/ckbill';
import { delCkcargo, recallPutBill } from '@/api/jxc/ckcargo';
import { listVessel } from "@/api/jxc/vessel";
export default {
  name: 'BillEdit',
  props: {

  },
  dicts: ['sys_measurement_unit', 'sys_origin_country', 'sys_curr_type'],
  data() {
    return {
      vesselList: [],
      rules: {
        cargoValue: [
          { required: true, message: "货物价值不能为空", trigger: "blur" }
        ],
        cargoNumber: [
          { required: true, message: "货物自然序号不能为空", trigger: "blur" }
        ],
        expiryDate: [
          { 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" }
        // ],
        billDate: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        billNumber: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
        inoutType: [
          { required: true, message: "出入库类型不能为空", trigger: "blur" }
        ],
        // voyageNo: [
        //   { required: true, message: "航次号不能为空", trigger: "blur" }
        // ],
        // vesselName: [
        //   { required: true, message: "船舶名称不能为空", trigger: "blur" }
        // ],
        cargoId: [
          { required: true, message: "货物不能为空", trigger: "change" }
        ],
        cargoWt: [
          { required: true, message: '货物重量不能为空', trigger: 'blur' }
        ],
        cargoNum: [
          { required: true, message: '货物件数不能为空', trigger: 'blur' }
        ],
        cargoVol: [
          { required: true, message: '货物体积不能为空', trigger: 'blur' }
        ],
        // cargoWt: [
        //   { validator: valueValid, trigger: "change" }
        // ],
        // cargoNum: [
        //   { validator: valueValid, trigger: "change" }
        // ],
        // cargoVol: [
        //   { validator: valueValid, trigger: "change" }
        // ],
        inStockId: [
          { required: true, message: "库场不能为空", trigger: "change" }
        ],
        custId: [
          { required: true, message: "货主不能为空", trigger: "change" }
        ],
        currType: [
          { required: true, message: "币种不能为空", trigger: "blur" },
        ],
        unitPrice: [
          { required: true, message: "货物单价不能为空", trigger: "blur" },
        ],
        originCountry: [
          { required: true, message: "原产国不能为空", trigger: "blur" },
        ],
      },
      // 货物
      cargoList: [],
      // 货主
      custList: [],
      // 库存列表
      stockList: [],
      form: {
        ckBillCargos: []
      },
      loading: false,
      selectedList: [],
      // 外部单据信息
      billInfo: {},
      // 外部入库明细
      modifyData: {},
      // 0修改 1新增 2查看
      type: 0,
    };
  },
  computed: {
    // 只读模式
    readonly() {
      return this.type === 2;
    },
    // 表格内容只读
    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: {
    getVesselList() {
      let param = {};
      listVessel(param).then(response => {
        this.vesselList = response.data;
      }).catch(e => {
      });
    },
    setVesselDetail(vesselId) {
      this.vesselList.forEach(ele => {
        if (ele.id == vesselId) {
          this.form.vesselName = ele.vesselName;
        }
      })
    },
    // type: 0修改 1新增 2查看，data: 新增传billInfo单据信息。修改时data为入库明细
    open({ type, data }) {
      this.type = type;
      //console.log("data", data);
      this.getCargoList();
      this.getCustList();
      this.getStockList();

      this.$nextTick(() => {
        let billId = null;
        if (type !== 1) {
          this.modifyData = data || {};
          billId = this.modifyData.billId;
        } else {
          this.billInfo = data || {};
          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;
            if (type === 1) {
              this.addBillTable();
            }
            this.loading = false;
            // this.$refs.table.doLayout();
          }).catch(e => {
            this.loading = false;
          });
        } else {
          if (type === 1) {
            this.addBillTable();
          }
        }
      });

    },
    rowStyle(row) {
      if (row.id && row.id === this.modifyData.id) {
        return {
          background: '#f0f9eb',
        }
      }
      return {};
    },
    // 检验表单
    validate(success) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.ckBillCargos.length === 0) {
            this.$message({
              message: '请添加入库明细',
              type: 'warning'
            });
            return;
          }

          const tempChoose = {};
          let findRepeat = false;
          let findValueEmpty = false;
          this.form.ckBillCargos.forEach(val => {
            if (tempChoose[val.cargoId] && tempChoose[val.cargoId] === val.inStockId) {
              findRepeat = true;
            }
            tempChoose[val.cargoId] = val.inStockId;
            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;
          }

          const validateForm = (index) => {
            this.$refs['form' + index].validate((validList, checkItem) => {
              if (validList) {
                if (index === this.form.ckBillCargos.length - 1) {
                  success();
                } else {
                  validateForm(index + 1);
                }
              } else {
                this.$message({
                  message: checkItem[Object.keys(checkItem)[0]][0].message,
                  type: 'warning'
                });
              }
            });
          };
          validateForm(0);
        }
      });
    },
    // submitStatus为true则为确认单据
    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 = '1';
        params.submitStatus = submitStatus;
        this.loading = true;
        putBill(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;
          recallPutBill(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);
      });

    },
    cancel(e) {
      this.$emit('close', e);
    },
    refreshList() {
      this.$emit('refresh');
    },
    selectionChange(sel) {
      this.selectedList = sel;
    },
    // 添加明细
    addBillTable() {
      this.form.ckBillCargos.splice(0, 0, {
        originCountry: '',
        cargoSpec: '',
        cargoNum: 0,
        cargoWt: 0,
        cargoVol: 0,
        cargoValue: 0,
      });
      this.$refs.table.bodyWrapper.scrollTop = this.$refs.table.bodyWrapper.scrollHeight;
      this.$nextTick(() => {
        this.$refs.table.bodyWrapper.scrollTop = 0;
      });
    },
    // 删除明细
    deleteSelectedBill() {
      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) => {

        });
      }
    },
    // 获取货物
    getCargoList() {
      listCargo({}).then(response => {
        this.cargoList = response.data;
      }).catch(e => {
      });
    },
    // 设置货物名称
    setCargoDetail(cargoId, form) {
      this.cargoList.forEach(ele => {
        if (ele.id == cargoId) {
          form.cargoName = ele.cargoName;
          form.hsCode = ele.hsCode;
          form.cargoSpec = ele.cargoSpec;
          form.originCountry = ele.originCountry;
        }
      })
    },
    // 设置客户
    setCustDetail(custId) {
      this.custList.forEach(ele => {
        if (ele.id == custId) {
          this.form.custName = ele.custName;
          this.form.custCode = ele.custCode;
        }
      })
    },
    // 获取客户
    getCustList() {
      listCust({}).then(response => {
        this.custList = response.data;
      }).catch(e => {
      });
    },
    // 设置仓库
    setStockDetail(stockId, form) {
      this.stockList.forEach(ele => {
        if (ele.id == stockId) {
          form.stockName = ele.stockName;
          form.stockCode = ele.stockCode;
        }
      })
    },
    // 获取仓位
    getStockList() {
      let param = {};
      listStock(param).then(response => {
        this.stockList = response.data;
      }).catch(e => {
      });
    },
  }
}
</script>

<style scoped>
.bill-edit {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

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

.margin-none {
  margin: 0;
}

::v-deep .el-descriptions--medium.is-bordered .el-descriptions-item__cell {
  /* padding: 10px; */
  padding: 0;
}

::v-deep .el-descriptions :not(.is-bordered) .el-descriptions-item__cell {
  /* padding-bottom: 12px; */
  padding-bottom: 0;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  /* border: 1px solid #e6ebf5; */
  /* padding: 12px 10px; */
  padding: 0;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  padding: 5px !important;
  min-width: 120px;
  max-width: 160px;
}
</style>
