<template>
  <el-dialog
    title="导入"
    :visible.sync="visible"
    width="85%"
    v-dialogDrag
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <!--      列设置-->
    <el-dialog title="提示" :visible.sync="showSetting" width="700px" v-dialogDrag append-to-body>
      <template slot="title">
        <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
            <span
              style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
            </span>
        </div>
      </template>
      <div>配置排序列数据（拖动调整顺序）</div>
      <div style="margin-left: 17px">
        <el-checkbox
          v-model="allCheck"
          label="全选"
          @change="allChecked"
        ></el-checkbox>
      </div>
      <div style="padding: 4px; display: flex; justify-content: center">
        <draggable
          v-model="setRowList"
          group="site"
          animation="300"
          @start="onStart"
          @end="onEnd"
          handle=".indraggable"
        >
          <transition-group>
            <div
              v-for="item in setRowList"
              :key="item.surface"
              class="listStyle"
            >
              <div style="width: 500px" class="indraggable">
                <div class="progress" :style="{ width: item.width + 'px' }">
                  <el-checkbox
                    :label="item.name"
                    v-model="item.checked"
                    :true-label="0"
                    :false-label="1"
                  >{{ item.name }}
                  </el-checkbox>
                </div>
              </div>
              <el-input-number
                v-model.number="item.width"
                controls-position="right"
                :min="1"
                :max="500"
                size="mini"
              ></el-input-number>
            </div>
          </transition-group>
        </draggable>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetting = false">取 消</el-button>
        <el-button @click="delRow" type="danger">重 置</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <div style="margin: 0 10px;float: right">
      <el-button
        icon="el-icon-setting"
        size="mini"
        circle
        @click="showSetting = !showSetting"
      ></el-button>
    </div>
    <el-table
      ref="table"
      :data="dataList"
      tooltip-effect="dark"
      stripe
      v-loading="loading"
      @selection-change="handleSelection"
      :height="tableHeight"
    >
      <el-table-column type="selection" width="50" align="center" fixed/>
      <el-table-column
        label="序号"
        type="index"
        width="50"
        fixed
        align="center"
      />
      <el-table-column
        v-for="(item, index) in getRowList"
        :key="index"
        :label="item.name"
        :width="item.width"
        :prop="item.label"
        align="center"
        :fixed="item.fixed"
        sortable
      >
        <template slot-scope="scope">
            <span v-if="item.label == 'fBsdate'">
              <el-date-picker
                v-model="scope.row.fBsdate"
                type="date"
                style="width: 100%"
                value-format="timestamp"
                placeholder="入库日期"
                @change="dateSelected(scope,'fBsdate')"
              >
              </el-date-picker>
            </span>
          <span v-else-if="item.label == 'fGoodsid'">
              <el-select
                filterable
                v-model="scope.row.fGoodsid"
                style="width: 100%"
                placeholder="请选择品名"
                @change="dateSelected(scope,'fGoodsid')"
              >
                <el-option
                  v-for="(item, index) in goodsOptions"
                  :key="index.fId"
                  :label="item.fName"
                  :value="item.fId"
                ></el-option>
              </el-select>
            </span>
          <span v-else-if="item.label == 'fBusinessType'">
              <el-select
                filterable
                v-model="scope.row.fBusinessType"
                style="width: 100%"
                placeholder="请选择商品属性"
                @change="dateSelected(scope,'fBusinessType')"
              >
                <el-option
                  v-for="(item, index) in fStorageTypeOptions"
                  :key="index.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </span>
          <span v-else-if="item.label == 'fMarks'">
              <el-input
                v-model="scope.row.fMarks"
                style="width: 100%"
                placeholder="请填写属性描述"
                @change="dateSelected(scope,'fMarks')"
              />
            </span>
          <span v-else-if="item.label == 'fWarehouseInformation'">
              <el-input
                placeholder="请选择"
                v-model="scope.row.fWarehouseInformation"
                @focus="getTreeselect(scope)"
              >
              </el-input>
            </span>
          <span v-else-if="item.label == 'fQty'">
              <el-input
                v-input-limit="0"
                v-model.number="scope.row.fQty"
                style="width: 100%"
                placeholder="件数"
                @change="dateSelected(scope,'fQty')"
              />
            </span>
          <span v-else-if="item.label == 'fGrossweight'">
              <el-input
                v-model.number="scope.row.fGrossweight"
                v-input-limit="2"
                style="width: 100%"
                placeholder="毛重"
                @change="dateSelected(scope,'fGrossweight')"
              />
            </span>
          <span v-else-if="item.label == 'fNetweight'">
              <el-input
                v-model.number="scope.row.fNetweight"
                v-input-limit="2"
                style="width: 100%"
                placeholder="净重"
                @change="dateSelected(scope,'fNetweight')"
              />
            </span>
          <span v-else-if="item.label == 'fPackagespecs'">
              <el-input
                v-model="scope.row.fPackagespecs"
                style="width: 100%"
                placeholder="包装规格"
              />
            </span>
<!--          <span v-else-if="item.label == 'fCntrno'">-->
<!--              <el-input-->
<!--                v-model="scope.row.fCntrno"-->
<!--                style="width: 100%"-->
<!--                placeholder="箱号"-->
<!--                v-Alphabet-->
<!--                @change="unRepeat(scope.row.fCntrno, scope.$index)"-->
<!--              />-->
<!--            </span>-->
          <span v-else-if="item.label == 'fTruckno'">
              <el-input
                v-model="scope.row.fTruckno"
                style="width: 100%"
                placeholder="车号"
                v-Alphabet
              />
            </span>
          <span v-else>{{ scope.row[item.label] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="80px"
        fixed="right">
        <template slot-scope="{row, $index}">
          <el-button
            @click.native.prevent="deleteRow($index)"
            size="small"
          >移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="选择库位"
      :data="treeselectList"
      :visible.sync="choiceWarehouse"
      width="30%"
      :close-on-click-modal="false"
      append-to-body
    >
      <treeselect
        v-model="treeselectList.fWarehouselocid"
        @select="getAlltree"
        :options="fWarehouseidOptions"
        :show-count="true"
        :disable-branch-nodes="true"
        placeholder="请选择归属库区"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="choiceWarehouse = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" :loading="buttonLoading">取 消</el-button>
      <el-button type="primary" @click="importData" :loading="buttonLoading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import {addSet, resetModule, select} from '@/api/system/set';
import draggable from "vuedraggable";
import {getToken} from "@/utils/auth";
import {listGoods} from "@/api/basicdata/goods";
import {treeselect} from "@/api/basicdata/warehouse";
import {getCrawler} from "@/api/warehouseBusiness/warehouseInStock"
import axios from "axios";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "noUpload",
  components: {
    draggable,
    Treeselect
  },
  props: {
    oldList: {
      type: Array,
      default: []
    },
    form: {
      type: Object
    },
  },
  data() {
    return {
      visible: false,
      dataList: [],
      loading: false,
      buttonLoading: false,
      tableHeight: '200',
      selection: [],
      goodsOptions: [],
      fStorageTypeOptions: [],
      fWarehouseidOptions: [],
      treeselectList: {
        fWarehouselocid: null,
      },
      choiceWarehouse: false,
      TreeIndex: null,
      bigDataToken: null,
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },

      // 设置列开关
      showSetting: false,
      setRowList: [],
      getRowList: [],
      showfCustomno: null,
      //自定义列宽
      allCheck: false,
      drag: false,
      tableDate: [
        {
          surface: "1",
          label: "fBsdate",
          name: "入库日期",
          checked: 0,
          width: 160,
        },
        {
          surface: "2",
          label: "fGoodsid",
          name: "品名",
          checked: 0,
          width: 100,
        },
        {
          surface: "3",
          label: "fBusinessType",
          name: "货物属性",
          checked: 0,
          width: 100,
        },
        {
          surface: "4",
          label: "fMarks",
          name: "属性详情",
          checked: 0,
          width: 100,
        },
        {
          surface: "5",
          label: "fWarehouseInformation",
          name: "库区",
          checked: 0,
          width: 100,
        },
        {
          surface: "6",
          label: "fQty",
          name: "件数",
          checked: 0,
          width: 100,
        },
        {
          surface: "7",
          label: "fGrossweight",
          name: "毛重(kg)",
          checked: 0,
          width: 130,
        },

        {
          surface: "8",
          label: "fNetweight",
          name: "净重(kg)",
          checked: 0,
          width: 130,
        },
        {
          surface: "9",
          label: "fPackagespecs",
          name: "包装规格",
          checked: 0,
          width: 100,
        },
        {
          surface: "10",
          label: "fCntrno",
          name: "箱号",
          checked: 0,
          width: 100,
        },
        {
          surface: "11",
          label: "fSealno",
          name: "封号",
          checked: 0,
          width: 180,
        },
        {
          surface: "12",
          label: "fTruckno",
          name: "车号",
          checked: 0,
          width: 100,
        },
      ],
    }
  },
  created() {
    this.setRowList = this.tableDate;
    this.getRowList = this.tableDate;
    this.getRow();
    listGoods({fStatus: 0, delFlag: 0}).then((response) => {
      this.goodsOptions = response.rows;
    });
    treeselect(this.form.fWarehouseid).then((response) => {
      this.fWarehouseidOptions = response.data;
    });
    this.getDicts("storage_type").then((response) => {
      this.fStorageTypeOptions = response.data;
    });
  },
  mounted() {
    this.$nextTick(() => {
      // 监听浏览器高度变化，改变表格高度
      window.onresize = () => {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 200
      }
    })
  },
  methods: {
    // 打开
    async init() {
      this.dataList = []
      await this.getConfigKey("bigData.token").then((response) => {
        this.bigDataToken = response.msg;
      });
      this.getList()
      this.visible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.visible = false;
      this.detailList = []
      this.$emit("closeDialog")
    },
    getList() {
      this.loading = true;
      axios({
          // url: 'http://192.168.1.114:9002/crawler/' + this.form.fMblno,
        url: 'https://crawler.tubaosoft.com/prod-api/crawler/data',
        method: 'post',
        data: {
          token: this.bigDataToken,
          param: this.form.fMblno,
          size: this.page.pageSize,
          page: this.page.pageNum
        },
        headers: {
          "Content-Type":'application/json'
        }
        }
      ).then(res => {
        if (res.data.code == 500) {
          return this.$message.error(res.data.msg)
        }
        //SEAL_NO 铅封号
        //CONTAINER_NO 箱号
        //CARGO_QUANTITY 件数
        //TOTAL_GROSS_WEIGHT 重量
        //BILL_OF_LADING_NO 提单号
        if (res.data.data[1].data.length == 0) {
          // XH 箱号
          // QFH1 铅封号
          // MZ 箱整重
          //TDH 提单号
          res.data.data[0].data.map(e => {
            e.fMblno = e.TDH;
            e.fSealno = e.QFH1;
            e.fGrossweight = e.MZ;
            e.fNetweight = e.MZ;
            e.fCntrno = e.XH;
          })
          // if (res.data.data[0].data.length == 1) {
          //   res.data.data[0].data.map(e => {
          //     e.fGrossweight = e.MZ;
          //     e.fNetweight = e.MZ;
          //   })
          // } else {
          //   res.data.data[0].data.map(e => {
          //     e.fGrossweight = '';
          //     e.fNetweight = '';
          //   })
          // }
          this.dataList = res.data.data[0].data
        } else {
          res.data.data[1].data.map(e => {
            e.fMblno = e.BILL_OF_LADING_NO;
            e.fSealno = e.SEAL_NO;
            // e.fQty = e.CARGO_QUANTITY;
            // e.fGrossweight = e.TOTAL_GROSS_WEIGHT;
            // e.fNetweight = e.TOTAL_GROSS_WEIGHT;
            e.fCntrno = e.CONTAINER_NO;
          })
          if (res.data.data[1].data.length == 1) {
            res.data.data[1].data.map(e => {
              e.fQty = e.CARGO_QUANTITY;
              e.fGrossweight = e.TOTAL_GROSS_WEIGHT;
              e.fNetweight = e.TOTAL_GROSS_WEIGHT;
            })
          } else {
            res.data.data[1].data.map(e => {
              e.fQty = '';
              e.fGrossweight = '';
              e.fNetweight = '';
            })
          }
          this.dataList = res.data.data[1].data
        }
        if (this.dataList.length > 0) {
          this.dataList.map(e => {
            this.$set(e, 'fBsdate', this.form.fBsdate);
            this.$set(e, 'fGoodsid', this.form.fGoodsid);
            this.$set(e, 'fBillstatus', 10)
          })
        }
        setTimeout(() => {
          this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 200
        }, 300)
        this.loading = false;
      }).finally(() => {
        this.loading = false;
      })
    },
    handleSelection(list) {
      this.selection = list
    },
    dateSelected(scope, name) {
      if (name === 'fBsdate') {
        this.dataList.forEach(item => {
          if (!item.fBsdate) this.$set(item, 'fBsdate', scope.row.fBsdate)
        })
      } else if (name === 'fGoodsid') {
        this.dataList.forEach(item => {
          if (!item.fGoodsid) this.$set(item, 'fGoodsid', scope.row.fGoodsid)
        })
      } else if (name === 'fBusinessType') {
        this.dataList.forEach(item => {
          if (!item.fBusinessType) this.$set(item, 'fBusinessType', scope.row.fBusinessType)
        })
      } else if (name === 'fMarks') {
        this.dataList.forEach(item => {
          if (!item.fMarks) this.$set(item, 'fMarks', scope.row.fMarks)
        })
      } else if (name === 'fQty') {
        this.dataList.forEach(item => {
          if (!item.fQty) this.$set(item, 'fQty', scope.row.fQty)
        })
      } else if (name === 'fGrossweight') {
        this.dataList.forEach(item => {
          if (!item.fGrossweight) this.$set(item, 'fGrossweight', scope.row.fGrossweight)
        })
      } else if (name === 'fNetweight') {
        this.dataList.forEach(item => {
          if (!item.fNetweight) this.$set(item, 'fNetweight', scope.row.fNetweight)
        })
      }
    },
    getTreeselect(row) {
      this.treeselectList.fWarehouselocid = row.row.fWarehouselocid
        ? row.row.fWarehouselocid
        : null;
      this.TreeIndex = row.$index;
      this.choiceWarehouse = true;
    },
    getAlltree(tree) {
      this.information = tree.fWarehouseInformation;
    },
    confirm() {
      this.$set(
        this.dataList[this.TreeIndex],
        "fWarehouseInformation",
        this.information
      );
      this.$set(
        this.dataList[this.TreeIndex],
        "fWarehouselocid",
        this.treeselectList.fWarehouselocid
      );
      this.choiceWarehouse = false;
    },
    unRepeat(row, index) {
      this.oldList.map((e) => {
        if (row == e.fCntrno) {
          this.dataList[index].fCntrno = null;
          this.$message.error("该箱号和明细表上的存在重复");
        }
      });
      this.dataList.map((e, i) => {
        if (index != i) {
          if (row && row == e.fCntrno) {
            this.dataList[index].fCntrno = null;
            this.$message.error("该箱号存在重复");
          }
        }
      });
    },
    importData() {
      if (this.dataList.length == 0) {
        return this.$message.error('表格未有数据，请关闭')
      }
      for (let item in this.dataList) {
        if (this.dataList[item].fBsdate == null) {
          return this.$message.error(
            "请选择第" + (Number(item) + 1) + "行的入库日期"
          );
        }
        if (this.dataList[item].fGoodsid == null) {
          return this.$message.error(
            "请选择第" + (Number(item) + 1) + "行的品名"
          );
        }
        if (this.dataList[item].fBusinessType == null) {
          return this.$message.error(
            "请选择第" + (Number(item) + 1) + "行的货物属性"
          );
        }
        if (this.dataList[item].fMarks == null) {
          return this.$message.error(
            "请输入第" + (Number(item) + 1) + "行的属性详情"
          );
        }
        if (this.dataList[item].fQty == null) {
          return this.$message.error(
            "请输入第" + (Number(item) + 1) + "行的件数"
          );
        }
        if (this.dataList[item].fGrossweight == null) {
          return this.$message.error(
            "请输入第" + (Number(item) + 1) + "行的毛重"
          );
        }
        if (this.dataList[item].fNetweight == null) {
          return this.$message.error(
            "请输入第" + (Number(item) + 1) + "行的净重"
          );
        }
      }
      this.buttonLoading = true;
      axios({
        url: 'https://crawler.tubaosoft.com/prod-api/crawler/charge',
        method: 'post',
        data: {
          token: this.bigDataToken,
          param: this.form.fMblno,
        },
      }).then(res => {
        if (res.data.code == 500) {
          return this.$message.error(res.data.msg)
        }
        this.$emit('addDetailList', this.dataList)
        this.buttonLoading = false;
        this.visible = false;
      }).finally(() => {
        this.buttonLoading = false;
      })
    },
    deleteRow(index) {
      this.dataList.splice(index, 1)
    },

    //列设置全选
    allChecked() {
      if (this.allCheck == true) {
        this.setRowList.map((e) => {
          return (e.checked = 0);
        });
      } else {
        this.setRowList.map((e) => {
          return (e.checked = 1);
        });
      }
    },
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
    },
    //重置列表
    delRow() {
      this.data = {
        tableName: "单号导入",
        userId: Cookies.get("userName"),
      };
      resetModule(this.data).then((res) => {
        if (res.code == 200) {
          this.showSetting = false;
          this.setRowList = this.tableDate;
          console.log(this.setRowList)
          this.getRowList = this.tableDate;
        }
      });
    },
    //保存列设置
    save() {
      this.showSetting = false;
      this.data = {
        tableName: "单号导入",
        userId: Cookies.get("userName"),
        sysTableSetList: this.setRowList,
      };
      addSet(this.data).then((res) => {
        this.getRowList = this.setRowList.filter((e) => e.checked == 0);
      });
    },
    //查询列数据
    getRow() {
      let that = this;
      this.data = {
        tableName: "单号导入",
        userId: Cookies.get("userName"),
      };
      select(this.data).then((res) => {
        if (res.data.length != 0) {
          this.getRowList = res.data.filter((e) => e.checked == 0);
          this.setRowList = res.data;
          this.setRowList = this.setRowList.reduce((res, item) => {
            res.push({
              surface: item.surface,
              label: item.label,
              name: item.name,
              checked: item.checked,
              width: item.width,
              fixed: item.fixed,
            });
            return res;
          }, []);
        }
      });
    },
  },
}
</script>

<style scoped>

</style>
