<template>
  <div>
    <basic-container>
      <avue-crud :option="option" :table-loading="loading" :data="assemblyForm.containersList"
        :permission="permissionList" :before-open="beforeOpen" v-model="form" id="out-table"
        :header-cell-class-name="headerClassName" ref="crud" :row-style="{ height: '20px' }"
        :cell-style="{ padding: '0px' }" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
        @selection-change="selectionChange" @refresh-change="refreshChange">
        <template slot="menuLeft">
          <div style="display: flex;align-items: center;justify-content: space-between">
            <div>
              <!--<el-button type="primary" size="small" @click="DistributionBox">配箱</el-button>-->
              <!--<el-button type="danger" size="small"-->
              <!--           :disabled="detailData.seeDisabled || pleasereviewType"-->
              <!--           @click="revokefun">撤销-->
              <!--</el-button>-->
              <!--<el-button type="danger" size="small"-->
              <!--           :disabled="detailData.seeDisabled || pleasereviewType"-->
              <!--           @click="wholeRevokefun">全部撤销-->
              <!--</el-button>-->
              <!-- <el-button type="warning" size="small" :disabled="detailData.seeDisabled || pleasereviewType || disabled"
                @click="cleanCntrNofun">清除箱号
              </el-button> -->
              <el-button type="success" size="small" plain :disabled="seeDisabled" @click.stop="equalDistribution2()">配箱
              </el-button>
              <el-button type="primary" size="small" :disabled="detailData.seeDisabled || pleasereviewType || showLock"
                @click="oneclickEditing">一键编辑
              </el-button>
              <el-button type="primary" size="small" :disabled="detailData.seeDisabled || pleasereviewType || disabled"
                @click="containersSubmitListfun">一键保存
              </el-button>
              <!-- <el-button type="danger" size="small" :disabled="detailData.seeDisabled || pleasereviewType || disabled"
                @click="handleDelete">一键删除
              </el-button> -->
              <el-button type="success" size="small"
                :disabled="detailData.seeDisabled || !assemblyForm.id || pleasereviewType || showLock"
                @click="oepnexcelBox">导入箱号铅封号
              </el-button>
              <el-button type="danger" size="small" :disabled="detailData.seeDisabled || pleasereviewType || showLock"
                @click="handleDelete">删除配箱
              </el-button>
              <el-button type="success" size="small" plain :disabled="detailData.seeDisabled"
                @click.stop="$refs.print.openDialog()">
                报 表
              </el-button>
              <!-- <el-button type="success" size="small"
                :disabled="detailData.seeDisabled || !assemblyForm.id || pleasereviewType || disabled"
                @click="excelBox = true">导入箱号,铅封号
              </el-button> -->
              <!--<el-button type="warning" size="small"-->
              <!--           :disabled="numberfalsefun() || assemblyForm.id"-->
              <!--           @click="equalDistribution">平均分配</el-button>-->
            </div>
            <!--<div>-->
            <!--    <el-button size="small">Copy</el-button>-->
            <!--    <el-button size="small">查看箱信息</el-button>-->
            <!--    <el-button size="small">校验箱信息</el-button>-->
            <!--</div>-->
          </div>
        </template>
        <!--<template slot-scope="scope" slot="menu">-->
        <!--    <el-button v-if="scope.row.edit" :type="scope.type" :size="scope.size" icon="el-icon-edit"-->
        <!--               @click.stop="rowSavefun(scope.row, scope.index)">保存-->
        <!--    </el-button>-->
        <!--    <el-button v-else :type="scope.type" :size="scope.size" icon="el-icon-edit"-->
        <!--               :disabled="detailData.seeDisabled || pleasereviewType"-->
        <!--               @click.stop="rowCellfun(scope.row, scope.index)">编辑-->
        <!--    </el-button>-->
        <!--    <el-button :type="scope.type" :size="scope.size" icon="el-icon-delete"-->
        <!--               :disabled="detailData.seeDisabled || pleasereviewType"-->
        <!--               @click.stop="rowDel(scope.row, scope.index)">删除-->
        <!--    </el-button>-->
        <!--</template>-->
        <template slot-scope="scope" slot="cntrNo">
          <el-input v-if="scope.row.edit" v-model="scope.row.cntrNo" maxlength='11' size="small" clearable
            placeholder="请输入箱号" @input="cntrNoInput(scope.row, 'cntrNo')"
            @change="verifyChange(scope.row, 'cntrNo')"></el-input>
          <span v-else>{{ scope.row.cntrNo }}</span>
        </template>
        <template slot-scope="scope" slot="sealNo">
          <el-input v-if="scope.row.edit" v-model="scope.row.sealNo" maxlength='11' size="small" clearable
            placeholder="请输入封号" @input="cntrNoInput(scope.row, 'sealNo')"></el-input>
          <span v-else>{{ scope.row.sealNo }}</span>
        </template>
        <template slot-scope="scope" slot="quantity">
          <el-input v-if="scope.row.edit" v-model="scope.row.quantity" size="small" clearable
            placeholder="请输入件数"></el-input>
          <span v-else>{{ Number(scope.row.quantity).toFixed(0) }}</span>
        </template>
        <template slot-scope="scope" slot="grossWeight">
          <el-input v-if="scope.row.edit" v-model="scope.row.grossWeight" size="small" clearable
            placeholder="请输入毛重"></el-input>
          <span v-else>{{ scope.row.grossWeight }}</span>
        </template>
        <template slot-scope="scope" slot="netWeight">
          <el-input v-if="scope.row.edit" v-model="scope.row.netWeight" size="small" clearable
            placeholder="请输入净重"></el-input>
          <span v-else>{{ scope.row.netWeight }}</span>
        </template>
        <template slot-scope="scope" slot="measurement">
          <el-input v-if="scope.row.edit" v-model="scope.row.measurement" size="small" clearable
            placeholder="请输入尺码"></el-input>
          <span v-else>{{ scope.row.measurement }}</span>
        </template>
        <template slot-scope="scope" slot="remarks">
          <el-input v-if="scope.row.edit" v-model="scope.row.remarks" size="small" clearable
            placeholder="请输入备注"></el-input>
          <span v-else>{{ scope.row.remarks }}</span>
        </template>
        <template slot-scope="scope" slot="marks">
          <el-input v-if="scope.row.edit" v-model="scope.row.marks" size="small" clearable
            placeholder="请输入MARKS"></el-input>
          <span v-else>{{ scope.row.marks }}</span>
        </template>
      </avue-crud>
    </basic-container>
    <business-reports :id="assemblyForm.id" :itemIds="itemIds" ref="print" businessValue="HYJK" classifyCode="业务"
      groupCode="配箱预览" :treeType="false" :type="1"></business-reports>
    <el-dialog title="导入箱号,铅封号" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false"
      v-dialog-drag>
      <avue-form :option="excelOption" v-model="excelForm" :table-loading="excelLoading" :upload-before="uploadBefore"
        :upload-after="onSuccess">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleGet">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
  </div>
</template>

<script>
import {
  containersDetail,
  containersSubmit,
  containersRemove,
  containersCleanBoxNo,
  containersRevoke,
  distributionBox,
  containersSubmitList,
  containersExportContainers, containersImportBoxNo, containersList
} from "@/api/iosBasicData/containers";
import { getAccurate } from "@/api/boxManagement/buyContainer/index.js";
import { mapGetters } from "vuex";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import bports from "@/views/iosBasicData/bports/index.vue";
import businessReports from "@/components/tradeAgency/businessReportsJK.vue";
import { bportsList } from "@/api/iosBasicData/bports";
import { getToken } from "@/util/auth";

export default {
  components: { SearchQuery, bports, businessReports },
  props: {
    assemblyForm: {},
    detailData: {},
    // 请核禁用
    pleasereviewType: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      headers: { "Blade-Auth": "Bearer " + getToken() },
      // 是否禁用
      extendedDisabled: false,
      // 装货港数据
      polData: [],
      // 附件配置
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-los/containers/importBoxNo"
          }
        ]
      },
      excelForm: {},
      excelLoading: false,
      excelBox: false,

      form: {},
      query: {},
      loading: false,
      // page: {
      //   pageSize: 10,
      //   currentPage: 1,
      //   total: 0
      // },
      selectionList: [],
      option: {
        stripe: true,
        height: '250',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        menu: false,
        column: [
          {
            label: "箱型",
            prop: "cntrTypeCode",
            width: "100",
          },
          {
            label: "箱号",
            prop: "cntrNo",
            width: "140",
            overHidden: true,
          },
          {
            label: "封号",
            prop: "sealNo",
            width: "140",
            overHidden: true,
          },
          // {
          //   label: "票数",
          //   prop: "ticketNumber"
          // },
          {
            label: "件数",
            prop: "quantity",
            width: "100",
            overHidden: true,
          },
          {
            label: "毛重(KGM)",
            prop: "grossWeight",
            width: "120",
            overHidden: true,
          },
          {
            label: "净重(KGM)",
            prop: "netWeight",
            width: "120",
            overHidden: true,
          },
          {
            label: "尺码/体积(CBM)",
            prop: "measurement",
            width: "140",
            overHidden: true,
          },
          {
            label: "POD堆场",
            prop: "podStationCname",
            width: "140",
            overHidden: true,
          },
          {
            label: "还箱日期",
            prop: "podEmptyContainerReturnDate",
            width: "140",
            overHidden: true,
          },
          {
            label: "备注",
            prop: "remarks",
            type: 'textarea',
            overHidden: true,
            width: 180,
            slot: true,
            minRows: 3,
            span: 24,
          },
          {
            label: "MARKS",
            prop: "marks",
            overHidden: true,
          },
          {
            label: "VGM总重(KGM)",
            prop: "vgmWeight",
            width: "140",
            overHidden: true,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.containers_add, false),
        viewBtn: this.vaildData(this.permission.containers_view, false),
        delBtn: this.vaildData(this.permission.containers_delete, false),
        editBtn: this.vaildData(this.permission.containers_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
  },
  methods: {
    // 输入自动大写
    cntrNoInput(row, name) {
      this.$set(row, name, row[name].toLocaleUpperCase().replace(/[\W]/g, ''))
    },
    verifyChange(row, name) {
      if (row[name]) {
        getAccurate({ accurate: row[name] }).then(res => {
          if (res.data.data.records.length == 0) {
            const regex = /^([a-zA-Z]{4})([0-9]{7})$/;
            if (regex.test(row[name])) {
              if (this.calculateCheckDigit(row[name]) == row[name][10]) {
                // this.$message.success('集装箱校验正确!')
              } else {
                this.$confirm(`箱号:${row[name]}是否强制加入系统?`, '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  // this.$message({
                  //   type: 'success',
                  //   message: '删除成功!'
                  // });
                }).catch(() => {
                  this.$set(row, [name], null)
                });
              }
            } else {
              this.$confirm(`箱号:${row[name]}是否强制加入系统?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // this.$message({
                //   type: 'success',
                //   message: '删除成功!'
                // });
              }).catch(() => {
                this.$set(row, [name], null)
              });
            }
          }
        })
      }
    },
    calculateCheckDigit(containerNo) {
      let charCode = "0123456789A?BCDEFGHIJK?LMNOPQRSTU?VWXYZ";
      let num = 0;
      for (let i = 0; i < 10; i++) {
        let idx = charCode.indexOf(containerNo[i]);
        idx = idx * Math.pow(2, i);
        num += idx;
      }
      return num = (num % 11) % 10;
    },
    uploadBefore(file, done, loading) {
      done();
      loading = true;
    },
    // 上传成功
    onSuccess(res, done, loading, column) {
      this.excelBox = false;
      // this.$message.success("导入成功！");
      this.containersListfun()
      loading = false;
      done();
    },
    // 箱列表
    containersListfun() {
      containersList(1, 100, { pid: this.assemblyForm.id }).then(res => {
        this.assemblyForm.containersList = res.data.data.records
      })
    },
    oepnexcelBox() {
      if (!this.assemblyForm.id) {
        this.$message({
          message: '请先点击右上角保存按钮，保存数据之后才能添加！',
          type: 'warning'
        });
        return
      }
      this.findObject(this.excelOption.column, "excelFile").action = "/api/blade-los/containers/importBoxNo?billId=" + this.assemblyForm.id
      this.excelBox = true
    },
    // 下载模板
    handleGet() {
      window.open(
        `/api/blade-los/containers/exportContainers?${this.website.tokenHeader
        }=${getToken()}&pid=${this.assemblyForm.id}`
      );
    },
    // 查询件数是否为零
    numberfalsefun() {
      if (!this.assemblyForm.containersList) {
        return false
      }
      for (let item of this.assemblyForm.containersList) {
        if (Number(item.quantity) >= 0) {
          return true
        } else {
          return false
        }
      }
    },
    // 平均分配
    equalDistribution() {
      if (this.assemblyForm.waitingBoxList.length <= 0) {
        this.$message({
          type: "warning",
          message: "请先添加集装箱数据!"
        });
        return
      }
      this.$confirm("确定平均分配?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit('equalDistribution')
      })
    },
    // 编辑
    rowCellfun(row, index) {
      this.$delete(row, 'edit')
      this.$set(row, 'edit', true)
    },
    // 保存
    rowSavefun(row) {
      this.$delete(row, 'edit')
      this.$set(row, 'edit', false)
      this.$emit('rowSavefun', row)
    },
    // 清除箱号
    cleanCntrNofun() {
      this.$confirm("确定将数据清除全部箱号?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let arr = this.assemblyForm.containersList.map(item => {
          return item.id
        })
        // 清除箱号接口
        containersCleanBoxNo(arr.join(',')).then(res => {
          this.$message({
            type: "success",
            message: "清除箱号成功!"
          });
          this.$emit('billsDetailfun')
        })
      })
    },
    // 全部撤销
    wholeRevokefun() {
      this.$confirm("确定将数据撤销全部?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let arr = this.assemblyForm.containersList.map(item => {
          return item.id
        })
        containersRevoke(arr.join(',')).then(res => {
          this.$message({
            type: "success",
            message: "全部撤销成功!"
          });
          this.$emit('billsDetailfun')
        })
      })
    },
    // 撤销
    revokefun() {
      if (this.selectionList.length > 0) {
        containersRevoke(this.selectionList[0].id).then(res => {
          this.$message({
            type: "success",
            message: "撤销成功!"
          });
          this.$emit('billsDetailfun')
        })
      } else {
        this.$message({
          type: "warning",
          message: "请选选择要撤销的数据!"
        });
      }
    },
    // 配像一键编辑
    oneclickEditing() {
      for (let item of this.assemblyForm.containersList) {
        this.$delete(item, 'edit')
        this.$set(item, 'edit', true)
      }
    },
    // 配箱批量保存
    containersSubmitListfun() {
      if (!this.assemblyForm.id) {
        this.$message.warning('请先大保存')
        return
      }
      this.$confirm("确定全部保存配箱?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        containersSubmitList(this.assemblyForm.containersList).then(res => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$emit('billsDetailfun')
        })
      })
    },
    equalDistribution2() {
      if (!this.assemblyForm.id) {
        this.$message({
          message: '请先点击右上角保存按钮，保存数据之后才能添加！',
          type: 'warning'
        });
        return
      }
      this.$confirm("是否确认配箱?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        distributionBox({ billId: this.assemblyForm.id }).then(res => {
          this.$message({
            type: "success",
            message: "操作成功!"
          })
          this.$emit('billsDetailfun')
        })
      })

    },
    rowSave(row, done, loading) {
      containersSubmit(row).then(() => {
        // this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      containersSubmit(row).then(() => {
        // this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    // 删除
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return containersRemove(row.id);
        })
        .then(() => {
          // this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$emit('billsDetailfun')
        });
    },
    // 一键删除
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return containersRemove(this.ids);
        })
        .then(() => {
          // this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$emit('billsDetailfun')
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        containersDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    // 当选择项发生变化时会触发该事件
    selectionChange(list) {
      this.selectionList = list
      // let arr = []
      // if (list.length > 1) {
      //     this.$refs.crud.toggleSelection() // 先清空所以选择的数据
      //     arr = [list[list.length -1]] // 获取最新点击的数组
      //     this.$refs.crud.toggleSelection(arr,true) // 把刚点击的数组变成选择状态
      // }else {
      //     arr = list
      // }
      // this.selectionList = arr
      // this.$emit('selectionChange',this.selectionList)
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    refreshChange() {
      console.log('刷新')
      // this.onLoad(this.page, this.query);
    },
    // onLoad(page, params = {}) {
    //   this.loading = true;
    //   containersList(page.currentPage, page.pageSize, {...Object.assign(params, this.query),pid:this.pid}).then(res => {
    //     const data = res.data.data;
    //     this.page.total = data.total;
    //       this.data = data.records
    //     this.loading = false;
    //     this.selectionClear();
    //   });
    // }
    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = ""
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one"
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two"
        }
      }
      return back;
    },

  }
};
</script>

<style scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}
</style>
