<template>
  <p-modal :title="config.title"
           :visible="visible"
           :dialogStyle="{ top: '20px' }"
           :width="'98%'"
           :confirmLoading="confirmLoading"
           @ok="handleOk"
           @cancel="handleCancel">
    <div v-if="visible" class="box-p20-bg">
      <p-grid-form ref="form" :items="searchItems" />

      <div style="height: 10px"></div>

      <!-- auto-width  dragle-->
      <p-table ref="mainlist"
               :rowKey="config.mainlist.rowKey"
               :remote-url="config.mainlist.remoteUrl"
               :columns="config.mainlist.columns"
               :remoteParams="mainRemoteParams"
               :remoteBefore="config.mainlist.remoteBefore || null"
               :doneBefore="config.mainlist.doneBefore"
               :data-source.sync="data"
               :autoLoad="false"
               dragle
               ellipsis
               size="small"
               :rowSelectFixed="true"
               :colorTransformRow="false"
               :hasRowSelectCheck="true"
               :selectedRowKeys.sync="list"
               :has-row-count="true"
               :rowSelectType="1"
               :scroll="{ y: 200, x: true }"
               @selectChange="mainSelectChange">
        <div slot="operator"
             slot-scope="text, record">
          <a v-for="(item, index) in config.mainlist.operators"
             :key="index"
             v-show="item.show ? item.show(record) : true"
             style="margin-left: 10px"
             @click.stop="item.click(record)">{{ item.label }}</a>
        </div>
      </p-table>

      <div style="height: 10px"></div>

      <!-- autoWidth dragle -->
      <p-table ref="Goods"
               :autoLoad="false"
               size="small"
               :rowKey="config.sublist.rowKey"
               :remote-url="config.sublist.GoodsremoteUrl"
               :remoteParams="remoteParams"
               :columns="config.sublist.columns"
               :data-source.sync="GoodsColumnsdata"
               :selectedRowKeys.sync="goodslist"
               :hasRowSelectCheck="true"
               dragle
               ellipsis
               :rowSelectFixed="true"
               :loading="subLoading"
               :colorTransformRow="false"
               :has-row-count="true"
               :pagination="false"
               :done="config.sublist.done || null"
               :rowSelectType="config.sublist.rowSelectType == 3 ? false : config.sublist.rowSelectType || 2"
               :scroll="{ y: 200, x: true }"
               @clickRow="clickRow">
        <!-- :rowSelectType="(config.sublist.rowSelectType == 3?false:config.sublist.rowSelectType) || 2" -->
        <div slot="operator"
             slot-scope="text, record">
          <a v-for="(item, index) in config.sublist.operators"
             v-show="item.show ? item.show(record) : true"
             :key="index"
             style="margin-left: 10px"
             @click.stop="item.click(record)">{{ item.label }}</a>
        </div>
      </p-table>
    </div>
  </p-modal>
</template>

<script>
import { forSelectText, getCargoOwner, getBldg } from '../../../utils'
import { inboundValidateModule } from "../../mixins/inboundValidate";
import { businessRuleModule } from "../../mixins/rule";

export default {
  name: 'InfoModal',
  mixins: [businessRuleModule, inboundValidateModule],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    config: {
      type: Object,
      default: null,
    },
    validateFun: {
      type: Function,
      default: null,
    },
  },
  model: {
    prop: 'visible',
    event: 'change',
  },
  data() {
    return {
      nConfig: null,
      data: [],
      GoodsColumnsdata: [],
      list: [],
      goodslist: [],
      mainRemoteParams: {},
      remoteParams: {},
      subLoading: false,
      searchItems: [],
      confirmLoading: false,
    }
  },
  watch: {
    data() {
      this.GoodsColumnsdata = []
      this.goodslist = []
    },
    visible(bool) {
      if (bool) {
        this.initData()
        this.$nextTick(() => {
          this.$refs.form.form.setFieldsValue({
            ...this.$store.state.user.warehouse,
          })
          this.getCargoOwnerFirst()
          this.getBldg()
        })
      } else {
        this.reset()
      }
    },
  },

  created() { },

  methods: {
    initData() {
      let config = this.config
      this.mainRemoteParams = config.mainlist.remoteParams
      // 添加排序
      config.mainlist.columns.forEach((t) => {
        if (!t.width) t.width = 150
        t.sorter = function (a, b) {
          let a1 = a[t.dataIndex] || ''
          let b1 = b[t.dataIndex] || ''
          if (typeof a1 === 'number') {
            return a1 - b1
          }
          return a1.localeCompare(b1)
        }
      })
      config.sublist.columns.forEach((t) => {
        t.sorter = function (a, b) {
          let a1 = a[t.dataIndex] || ''
          let b1 = b[t.dataIndex] || ''
          if (typeof a1 === 'number') {
            return a1 - b1
          }
          return a1.localeCompare(b1)
        }
      })
      if (
        Array.isArray(config.mainlist.operators) &&
        config.mainlist.operators.length > 0 &&
        config.mainlist.columns[config.mainlist.columns.length - 1].key != 'operator'
      ) {
        config.mainlist.columns.push({
          title: '操作',
          dataIndex: 'operator',
          key: 'operator',
          fixed: 'right',
          width: 140,
          scopedSlots: { customRender: 'operator' },
        })
      }

      if (
        Array.isArray(config.sublist.operators) &&
        config.sublist.operators.length > 0 &&
        config.sublist.columns[config.sublist.columns.length - 1].key != 'operator'
      ) {
        config.sublist.columns.push({
          title: '操作',
          dataIndex: 'operator',
          key: 'operator',
          fixed: 'right',
          width: 200,
          scopedSlots: { customRender: 'operator' },
        })
      }
      this.searchItems = [
        ...config.girdform,
        {
          span: 6,
          type: 'buttonGroup',
          style: { textAlign: 'center' },
          options: [
            {
              value: '查询',
              icon: 'search',
              btnType: 'primary',
              style: 'margin-right:10px',
              on: {
                click: (event, form) => {
                  form.validateFields((errs, vals) => {
                    if (errs) {
                      return
                    }
                    // this.GoodsColumnsdata = [];
                    this.goodslist = []
                    let params = {}
                    if (this.config.mainlist.remoteParams) {
                      params = { ...this.config.mainlist.remoteParams }
                    }
                    this.mainRemoteParams = { ...params, ...vals }
                  })
                },
              },
            },
            {
              value: '重置',
              icon: 'redo',
              on: {
                click: () => {
                  this.$nextTick(() => {
                    this.$refs.form.form.resetFields()
                  })
                },
              },
            },
          ],
        },
      ]
      forSelectText([config.mainlist.columns, config.sublist.columns]).then((arr) => {
        config.mainlist.columns = arr[0]
        config.sublist.columns = arr[1]
        this.nConfig = config
      })
    },

    reloadMain() {
      this.list = []
      this.goodslist = []
      this.GoodsColumnsdata = []
      this.$refs.mainlist.reload()
    },

    mainSelectChange(selectedKeys, selectedRows) {
      if (!Array.isArray(selectedKeys) || selectedKeys.length === 0 || !selectedKeys[0]) {
        return
      }
      // console.log('selectedKeys',selectedKeys);
      let remoteParams = this.config.sublist.remoteBefore([...selectedKeys], selectedRows[0])
      this.remoteParams = remoteParams
      this.goodslist = []
    },

    getdata(subSelected) {
      if (this.list.length == 0) {
        return
      }
      if (subSelected && this.goodslist.length == 0) {
        return
      }
      let rowKey = this.config.mainlist.rowKey
      let rowKey2 = this.config.sublist.rowKey
      let mainlist = this.data.filter(tt => {
        if (this.list.some(ttt => ttt == tt[rowKey])) return true;
        return false;
      });

      let sublist = subSelected ?
        this.GoodsColumnsdata.filter(tt => {
          if (this.goodslist.some(ttt => ttt == tt[rowKey2])) return true;
          return false;
        }) : this.GoodsColumnsdata
      let data = {
        mainlist,
        sublist,
      }
      return data
    },

    getSelectedMainItem() {
      return this.data.find((t) => this.list.some((tt) => tt == t[this.config.mainlist.rowKey]))
    },

    clickRow(selectedRowKeys, key) {
      let n = 0
      this.goodslist.forEach((t) => {
        if (t == key) n++
      })
      if (n > 1) {
        this.goodslist = this.goodslist.filter((t) => t != key)
      }
    },

    handleOk(e) {
      // 明细表 rowSelectType === 3 不用勾选
      if (this.config.sublist.rowSelectType !== 3 && this.goodslist.length == 0) {
        this.$message.warning('请选择明细')
        return
      }
      let data = this.getdata(this.config.sublist.rowSelectType !== 3)

      let items = data.sublist.map(tt => ({
        id: tt.itemId,
        name: tt.itemName,
        categoryCode: tt.categoryCode,
        cargoOwnerId: tt.mtlOwnerId,
        shipperType: data.mainlist[0].shipperType,
        shipperid: data.mainlist[0].shipperid,
      }));
      this.getCargoOwnerProp(data.mainlist[0].mtlOwnerId, items).then(res => {
        if (res) {
          // 自定义验证
          this.handleValidate(data);
        }
      })

    },

    handleCancel(e) {
      this.reset()
      this.$emit('change', false)
    },

    handleValidate(data) {
      if (!this.validateFun) {
        this.reset()
        this.$emit('change', false, data)
        return
      }
      let result = this.validateFun(data)
      if (result instanceof Promise) {
        this.confirmLoading = true
        result.then((res) => {
          this.confirmLoading = false
          if (!res) {
            return
          }
          this.reset()
          this.$emit('change', false, data)
        })
      } else if (result) {
        this.reset()
        this.$emit('change', false, data)
      }
    },

    reset() {
      this.data = []
      this.GoodsColumnsdata = []
      this.list = []
      this.goodslist = []
      this.remoteParams = {}
    },
    //获取货主信息
    getCargoOwnerFirst() {
      getCargoOwner().then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        if (res.data.list.length > 0) {
          this.$refs.form.form.setFieldsValue({
            cargoOwnerId: res.data.list[0].companyId,
            mtlOwnerId: res.data.list[0].companyId,
            cargoOwnerCode: res.data.list[0].companyCode,
            cargoOwnerName: res.data.list[0].companyName,
          })
        }
      })
    },

    //获取建筑物
    getBldg() {
      var warehouseId = this.$refs.form.form.getFieldsValue().warehouseId
      var params = {
        warehouseId: warehouseId,
        pageNum: 1,
        pageSize: 10,
      }
      getBldg(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        if (res.data.list.length < 2) {
          this.$refs.form.form.setFieldsValue({
            bldgId: res.data.list[0].bldgId,
            bldgCode: res.data.list[0].bldgCode,
            bldgName: res.data.list[0].bldgName,
          })
        }
      })
    },

  },
}
</script>

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