<template>
  <div>
    <p-grid-form
      :ref="tablecolumns.gridform.ref"
      :span="8"
      :items="tablecolumns.gridform.items"
      @submit="hanlderSubmit"
    />
    <!-- 策略 -->
    <!-- :active-tab-key="tablecolumns.MainTable.title" -->

    <p-table
      :id="$route.meta.menuId + '_25580'"
      bordered
      v-if="!tablecolumns.MainTable.edit"
      :selectedRowKeys.sync="MainTableselectedRowKeys"
      :remote-url="tablecolumns.MainTable.remoteUrl"
      :ref="tablecolumns.MainTable.ref"
      :row-key="tablecolumns.MainTable.rowkey"
      :columns="tablecolumns.MainTable.columns"
      :doneBefore="tablecolumns.MainTable.doneBefore"
      :data-source.sync="data"
      dragle
      :rowSelectFixed="true"
      :remoteBefore="tablecolumns.MainTable.remoteBefore"
      :remoteParams="MainTableremoteParams"
      :rowSelectType="2"
      :autoLoad="false"
      @selectChange="selectedRowsfun"
      :scroll="tablecolumns.MainTable.scroll || {}"
    >
      <!-- :row-selection="{ fixed: true, onChange: selectedRowsfun }" -->
    </p-table>

    <p-table-edit-pro
      :id="$route.meta.menuId + '_96786'"
      v-if="tablecolumns.MainTable.edit"
      bordered
      size="small"
      :selectedRowKeys.sync="MainTableselectedRowKeys"
      :remote-url="tablecolumns.MainTable.remoteUrl"
      :ref="tablecolumns.MainTable.ref"
      dragle
      auto-width
      :rowSelectFixed="true"
      :row-key="tablecolumns.MainTable.rowkey"
      :columns="tablecolumns.MainTable.columns"
      :doneBefore="tablecolumns.MainTable.doneBefore"
      :remoteBefore="tablecolumns.MainTable.remoteBefore"
      :data-source.sync="data"
      :remoteParams="MainTableremoteParams"
      :rowSelectType="2"
      @selectChange="selectedRowsfun"
      :autoLoad="false"
      :scroll="tablecolumns.MainTable.scroll || {}"
    >
      <!-- :row-selection="{ fixed: true, onChange: selectedRowsfun }" -->
      <template slot="pendingQty" slot-scope="text, record, index">
        <p-input-number
          style="width: 80px"
          @change="(e) => onChangenumpendingQty(e, record, index)"
          :value="text"
          :min="0"
          :max="parseInt(record.upkeepQty1)"
        />
      </template>

      <!-- planUpkeepDate -->

      <template slot="planUpkeepDate" slot-scope="text, record, index">
        {{ moment().format("YYYY-MM-DD") }}
      </template>
      <template slot="upkeepQty" slot-scope="text, record, index">
        <p-input-number
          v-if="text != record.stockQty"
          style="width: 80px; color: red"
          @change="(e) => onChangenum(e, record, index)"
          :value="text"
          :min="0"
          :max="parseInt(record.upkeepQty1)"
        />
        <p-input-number
          v-else
          style="width: 80px"
          @change="(e) => onChangenum(e, record, index)"
          :value="text"
          :min="1"
          :max="parseInt(record.upkeepQty1)"
        />
      </template>

      <template slot="upkeepQty1" slot-scope="text, record, index">
        <p-input-number
          style="width: 80px"
          @change="(e) => onChangenumadd(e, record, index)"
          :value="text"
          :min="1"
          :max="parseInt(record.upkeepQty1)"
        />
      </template>

      <!-- upkeepQty -->

      <template slot="stockQty" slot-scope="text, record, index">
        <span v-if="text != record.upkeepQty" style="color: red">{{ text }}</span>
        <span v-else>{{ text }}</span>
      </template>

      <template slot="upkeepConclusion" slot-scope="text, record, index">
        <!-- <p-checkbox :key="index" @change="(e, key) => onChangecheckboxCol(e, item.key)">{{ item.title }}</p-checkbox> -->
        <!-- {{ text }} -->
        {{ text == "0" ? (text = "待处理") : text == "1" ? (text = "合格") : text == "2" ? (text = "不合格") : "" }}
      </template>
      <template v-for="(item, index) in aaa" v-slot:[item.slots.title]>
        <!-- <p-checkbox :key="index" @change="(e, key) => onChangecheckboxCol(e, item.key)">{{ item.title }}</p-checkbox> -->
        <div class="hover" :key="index" @click="onChangecheckboxCol(vtype, item.key)">{{ item.title }}</div>
      </template>

      <template v-for="(item, index) in aaa" :slot="item.scopedSlots.customRender" slot-scope="text, record">
        <!-- {{ item }} -->
        <a-checkbox
          :key="index"
          @change="(e, key) => onChangecheckbox(e, text, record, index, item.dataIndex)"
          :checked="record[item.dataIndex]"
        ></a-checkbox>
      </template>
    </p-table-edit-pro>

    <!--规则表  -->
  </div>
</template>

<script>
import moment from "moment";
const empdata = {
  code: null,
  dcId: null,
  warehouseId: "",
  cargoOwnerId: null,
  batchId: null,
  planId: "",
  planCode: "",
  itemId: "",
  itemCode: "",
  lotNo: null,
  locatorId: "",
  locatorCode: null,
  stockQty: null,
  upkeepQty: null,
  pendingQty: null,
  itemType: null,
  upkeepOperator: null,
  status: null,
  sourceType: null,
  upkeepConclusion: null,
  checkConclusion: null,
  recheckConclusion: null,
  conclusion: null,
  processOpinion: null,
  checkOperator: null,
  checkOpinion: null,
  recheckOperator: null,
  recheckOpinion: null,
  checkWaiGuan: false,
  checkBaoZhuang: false,
  checkChenChuTiaoJian: false,
  checkFanDuo: false,
  checkChuShi: false,
  checkJiaShi: false,
  checkShenWen: false,
  checkJiangWen: false,
  checkTongFeng: false,
  checkChuChen: false,
  checkChongZhu: false,
  checkFaMei: false,

  checkBiGuang: false,
  checkChaoJie: false,
  checkZheGuang: false,
  //   checkShangDou: false,
  //   checkPoSun: false,
  qualityStatus: null,
  thsTatus: null,
  pendingReason: null,
  planUpkeepDate: null,
  upkeepDate: null,
  checkDate: null,
  recheckDate: null,
  remark: null,
  pdateFrom: null,
  validUntil: null,
  bldgId: null,
  upkeepType: null,
  manufacturerName: "",
  itemHealthListedLicensor: null,
};
import data from "./data.js";
import { setwarehouse } from "../../mixin/warehousemixin.js";
import { setCargoOwner } from "@/views/kzyWMS/utils/setCargoOwner";
import { registerCoordinateSystem } from "echarts/core";
import { diffOption } from "@/views/kzyWMS/utils/index.js";
export default {
  mixins: [setwarehouse, setCargoOwner],
  name: "MainTable",
  props: {
    tablecolumns: {
      type: Object,
      default: () => {},
    },
    title: {
      type: String,
      default: "不合格品申请",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    config: {
      type: Object,
      default: null,
    },
  },
  model: {
    prop: "visible",
    event: "change",
  },
  data() {
    return {
      pagination: {
        // total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        // showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"], //每页中显示的数据
        // showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      vtype: true,
      aaa: [],
      selectedRowList: [],
      selectedRowKeys: [],
      //   data,
      data: [],
      MainTableselectedRowKeys: [],
      MainTableremoteParams: {},
      SubTableremoteParams: {},
      rowkey: "id",
      SubTabledata: [],
      ref: "aaa",
      addType: false,
    };
  },
  mounted() {},
  created() {
    diffOption(this.tablecolumns.MainTable.columns).then((res) => {
      this.tablecolumns.MainTable.columns = res;
    });

    let a = this.tablecolumns.MainTable.columns.filter((item) => {
      return item.slots && item.scopedSlots ? item : null;
    });
    // console.log(a);
    this.aaa = a;
  },
  computed: {
    key() {
      return this.tablecolumns.MainTable.title;
    },
    key1() {
      return this.tablecolumns.SubTable.title;
    },
    tabList() {
      let that = this;
      return [
        {
          key: that.tablecolumns.MainTable.title,
          tab: that.tablecolumns.MainTable.title,
        },
      ];
    },
    tabList1() {
      let that = this;
      return [
        {
          key: that.tablecolumns.SubTable.title,
          tab: that.tablecolumns.SubTable.title,
        },
      ];
    },
  },
  methods: {
    onChangependingQty(e, record, index) {
      console.log(arguments);
    },
    //清空data
    cleanData() {
      this.data = [];
      this.MainTableselectedRowKeys = [];
    },
    createRow() {
      this.$refs[this.tablecolumns.MainTable.ref].createRow(empdata);
    },
    cleanSeleRow() {
      this.selectedRowKeys = [];
      this.selectedRowList = [];
    },

    //获取data
    getData() {
      this.$refs[this.tablecolumns.MainTable.ref].validateFields(function (error, values, selectData) {
        if (error) return;
        if (!error) {
          console.log(selectData);
          return selectData;
        }
      });
      //   return this.data
    },
    getData1() {
      return this.data;
    },
    setRowQTy(id, value) {
      console.log(id, value);
      this.data.forEach((item) => id == item.id && (item.upkeepQty = value));
    },
    //获取选择行数 拆分
    getSelectRowSplit() {
      console.log(this.selectedRowList);
      if (this.selectedRowList.length != 1) {
        this.$message.warning("请选择一行进行拆分!");
        return;
      }
      if (this.selectedRowList[0].upkeepQty == 1) {
        this.$message.warning("数量为1,不能拆分");
        return;
      }
      let ss = this.data.findIndex((item) => item.id == this.selectedRowList[0].id);
      this.selectedRowList[0].upkeepQty--;
      let newRows = {
        ...this.selectedRowList[0],
        id: this.selectedRowList[0].id + "_copy_" + Math.floor(Math.random() * 1000),
        creatRowid: this.selectedRowList[0].id,
        upkeepQty: 1,
      };
      this.data.push(newRows);

      //   this.data = [...this.data]
      let arr = [...this.data];
      this.data = [];
      this.$nextTick(() => {
        this.data = arr;
      });
      console.log(this.data);

      //   this.selectedRowList = []

      //   return {
      //     id: this.selectedRowList[0].id,
      //     creatRowid: newRows.id,
      //     data: this.data
      //   }
    },
    //翻跺正行全选
    onChangecheckboxCol(value, key) {
      console.log(value, key);
      let s = this.data.every((item) => {
        if (!item[key]) {
          return false;
        } else {
          return true;
        }
      });
      console.log(s);
      if (s) {
        this.checkboxs(this.data, key, false);
        return;
      }
      this.checkboxs(this.data, key, true);
    },
    checkboxs(data, key, value) {
      data.forEach((item) => {
        key == "checkChuShi" && value && (item.checkJiaShi = false);
        key == "checkJiaShi" && value && (item.checkChuShi = false);
        key == "checkJiangWen" && value && (item.checkShenWen = false);
        key == "checkShenWen" && value && (item.checkJiangWen = false);
        key == "checkZheGuang" && (item.checkBiGuang = false);
        key == "checkBiGuang" && (item.checkZheGuang = false);
        item[key] = value;
        console.log(item[key]);
      });
    },
    onChangecheckbox(e, text, record, index, key) {
      console.log(e, text, record, index, key);
      record[key] = e.target.checked;
      console.log(key, record[key], record);
      if (!e.target.checked) {
        return;
      }
      key == "checkChuShi" && (record.checkJiaShi = false);
      key == "checkJiaShi" && (record.checkChuShi = false);
      key == "checkShenWen" && (record.checkJiangWen = false);
      key == "checkJiangWen" && (record.checkShenWen = false);
      key == "checkZheGuang" && (record.checkBiGuang = false);
      key == "checkBiGuang" && (record.checkZheGuang = false);
    },
    //获取gridform数据
    getgridformdata() {
      let data;
      this.$refs[this.tablecolumns.gridform.ref].form.validateFields((err, value) => {
        if (!err) {
          //   console.log(value)
          data = value;
        }
      });
      if (data) {
        return data;
      }
    },
    reload() {
      //   this.$refs[this.tablecolumns.MainTable.ref].reload();
      this.$refs[this.tablecolumns.gridform.ref].form.validateFields((err, value) => {
        if (!err) {
          console.log(value);
          this.MainTableremoteParams = { ...this.MainTableremoteParams, ...value };
          this.SubTabledata = [];
        } else {
          this.$message.warning("请选择货主和仓库名称");
        }
      });
    },
    selectedRowsfun(selectedRowKeys, selectedRow) {
      console.log(selectedRowKeys, selectedRow);
      let indexlist = selectedRow.map((item) => item._row_count - 1);
      console.log(indexlist);
      if (this.$refs[this.tablecolumns.MainTable.ref].clearAllColRule) {
        this.$refs[this.tablecolumns.MainTable.ref].clearAllColRules();
        this.$refs[this.tablecolumns.MainTable.ref].setIndexByColRules("recheckConclusion", indexlist);
      }
      //   this.$refs[this.tablecolumns.MainTable.ref].clearAllColRules()
      //   this.$refs[this.tablecolumns.MainTable.ref].setIndexByColRules('recheckConclusion', indexlist)
      this.selectedRowKeys = selectedRowKeys;

      this.selectedRowList = selectedRow;
    },
    getselectedRowsfun() {
      let data;
      data = this.selectedRowList;
      return data;
      //   return this.selectedRowList
    },

    //获取选择行 +表单验证
    getselectedRowsfunss() {
      let aaa = this.data.filter((tt) => this.selectedRowKeys.some((t) => t == tt.id));
      aaa = aaa.map((item) => item._row_count - 1);
      //   console.log(aaa);
      //   console.log(this.$refs[this.tablecolumns.MainTable.ref]);
      let data = [];
      aaa.forEach((item) => {
        this.$refs[this.tablecolumns.MainTable.ref].validateFields(item, function (error, values, selectData) {
          console.log(error, values, selectData);
          if (error) return;
          if (!error) {
            // console.log(error, selectData)

            data.push(values[0]);
          }
        });
      });
      //   console.log(data);
      if (aaa.length > 0) {
        return data;
      } else {
        return false;
      }

      //   })
      //   this.$refs[this.tablecolumns.MainTable.ref].setIndexByColRules('recheckConclusion', 1)
    },
    getselectedRowsfun1() {
      let data = [];

      console.log(this.selectedRowKeys);
      this.$refs[this.tablecolumns.MainTable.ref].validateFields(
        this.selectedRowKeys,
        function (error, values, selectData) {
          console.log(error);
          if (!error) {
            console.log(values, selectData);
            data = values;
          }
        }
      );

      console.log(data);
      return data;
    },
    details(data) {
      this.$emit("details", data);
    },

    onChange(e, record, index) {
      console.log(e, record, index);
      this.data[index].auditText = e.target.value;
      console.log(this.data[index]);
    },
    onChangenumadd(e, record, index) {
      //   console.log(e, record, index)
      this.data[index].upkeepQty = e;
      //   console.log(this.data[index])
    },
    onChange(e, record, index) {
      //   console.log(e, record, index)
      this.data[index].auditText = e;
      console.log(this.data[index]);
    },
    onChangenum(e, record, index) {
      console.log(e, record, index);
      console.log(this.data);
      let { planStockQty, pendingQty } = record;
      this.data[index].upkeepQty = e;
      this.data[index].pendingQty = planStockQty - e;
      let a = this.data.slice(1).reduce((total, num) => {
        // console.log(total, num, num.upkeepQty)
        if (record.id == num.id) {
          //   console.log(total, num.upkeepQty)
          return total + num.upkeepQty;
        } else {
          return total;
        }
      }, 0);
      //   console.log(a)
      this.data.forEach((item) => {
        // console.log(item, record)
        if (item.id == record.id.replace(/_copy_\d*/, "") && record.creatRowid) {
          //   console.log('test')
          console.log("test", item, record);
          //   item.upkeepQty = item.stockQty - a
          let ss = this.data.reduce((total, num) => {
            if (record.creatRowid == num.creatRowid) {
              return total + num.upkeepQty;
            } else {
              return total;
            }
          }, 0);
          item.upkeepQty = item.stockQty - ss;
        }
      });
      //   this.data[0].upkeepQty = this.data[0].stockQty - a
      //   this.data[0].upkeepQty = this.data[0].upkeepQty - e
    },
    onChangenumpendingQty(e, record, index) {
      // ecord.planStockQty - +e.record.upkeepQty;
      let { planStockQty, upkeepQty } = record;

      this.data[index].pendingQty = e;
      this.data[index].upkeepQty = planStockQty - e;
    },
    Sub() {
      this.$refs[this.tablecolumns.gridform.ref].form.validateFields((err, value) => {
        if (!err) {
          console.log(value);
          this.MainTableremoteParams = { ...this.MainTableremoteParams, ...value };
        } else {
          this.$message.warning("请选择货主和仓库名称");
        }
      });
    },
    hanlderSubmit(event, form) {
      event.preventDefault();
      this.$refs[this.tablecolumns.gridform.ref].form.validateFields((err, value) => {
        if (!err) {
          console.log(value);
          this.MainTableremoteParams = { ...this.MainTableremoteParams, ...value };
          this.SubTabledata = [];
        } else {
          this.$message.warning("请选择货主和仓库名称");
        }
      });
    },
    //获取表信息
    gettable(value) {
      console.log(value);
      this.addType = false;
      this.selectedRowList = [];
      this.MainTableremoteParams = { ...this.MainTableremoteParams, ...value };
    },
    setType(bool) {
      this.addType = bool;
    },
  },
};
</script>

<style>
.box-p20-bg {
  margin-bottom: 20px;
  background: #fff;
}
</style>
