<template>
  <div class="collection">
    <p-card :style="{ marginTop: '20px' }">
      <template slot="title">
        <div class="card-custom-title">
          <div>集货区管理</div>
          <div>
            <p-button type="primary" icon="lock" @click="SetType(true)" style="margin-left: 10px">暂存类型容量设置</p-button>
            <p-button type="primary" icon="lock" style="margin-left: 10px" @click="lock(true)">锁定</p-button>
            <p-button type="primary" icon="lock" style="margin-left: 10px" @click="unlock(true)">解锁</p-button>
            <p-button type="primary" icon="plus" style="margin-left: 10px" @click="showModal(true)">新增</p-button>
            <p-button type="primary" icon="edit" style="margin-left: 10px" @click="batchEdit(true)">批量修改</p-button>
          </div>
        </div>
      </template>

      <div class="plg-inner-form-mb">
        <p-grid-form
          ref="search"
          :span="8"
          :label-col="{ span: 6 }"
          :items="items"
          @submit="hanlderSubmit"
        ></p-grid-form>
      </div>
      <p-table
        :columns="columns"
        :data-source.sync="data"
        :has-row-count="true"
        rowKey="stageId"
        @change="paginationChange"
        :pagination="pagination"
        :loading="loading"
        bordered
        auto-width
        :rowSelectFixed="true"
        :scroll="{ x: 1500 }"
        :selectedRowKeys.sync="selectedRowKeys"
      >
        <template slot="isEnable" slot-scope="text"> {{ text ? '启用' : '禁用' }} </template>
        <template slot="action" slot-scope="text, record">
          <a @click="showModal(false, record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="您确定要删除吗?" ok-text="确认" cancel-text="取消" @confirm="delSingle(record)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </p-table>
    </p-card>
    <p-modal
      :title="actionType ? '集货区新增' : '集货区修改'"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      width="80%"
    >
      <p-grid-form ref="modelForm" :span="8" :label-col="{ span: 6 }" :items="modalItems" />
    </p-modal>
    <!-- 集货区类型列表 -->
    <p-modal
      title="暂存类型容量设置"
      :visible="SetTypevisible"
      :confirm-loading="confirmLoading"
      @ok="handleCancelTypeVisible"
      @cancel="handleCancelTypeVisible"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      width="80%"
    >
      <div class="card-custom-title">
        <div>
          <p-button type="primary" icon="plus" style="margin-left: 10px" @click="showModalType(true)">新增</p-button>
        </div>
      </div>
      <div class="plg-inner-form-mb">
        <p-grid-form
          ref="search"
          :span="8"
          :label-col="{ span: 6 }"
          :items="TypeColumns.items"
          @submit="hanlderSubmitType"
        />
      </div>

      <p-table
        :ref="TypeColumns.ref"
        :columns="TypeColumns.columns"
        :data-source.sync="TypeData"
        :remote-url="TypeColumns.remoteUrl"
        :has-row-count="true"
        rowKey="id"
        bordered
      >
        <template slot="action" slot-scope="text, record">
          <a @click="showModalType(false, record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="您确定要删除吗?" ok-text="确认" cancel-text="取消" @confirm="delSingleType(record)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </p-table>
    </p-modal>
    <!-- 集货区类型弹窗 -->
    <p-modal
      :title="actionType1 ? '集货区类型新增' : '集货区类型修改'"
      :visible="visibleType"
      :confirm-loading="confirmLoading"
      @ok="handleOkType"
      @cancel="visibleType = false"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      width="50%"
    >
      <p-grid-form
        ref="modelFormType"
        :span="8"
        :label-col="{ span: 12 }"
        :items="TypeColumns.modalItems"
      />
    </p-modal>
    <!-- 批量修改弹窗 -->
    <p-modal
      title="批量修改(输入框为空则不修改该属性)"
      :visible="visibleEditType"
      :confirm-loading="confirmEditLoading"
      @ok="handleOkEditType"
      @cancel="visibleEditType = false"
      :destroyOnClose='true'
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      width="50%"
    >
      <p-grid-form
        ref='modelEditType'
        :span='8'
        :label-col='{ span: 6}'
        :items='modalEditItems'
      />
    </p-modal>
  </div>
</template>

<script>
import { setwarehouse } from './config/warehousemixin.js'
import { items, modalItems, columns, TypeColumns, modalEditItems } from './config/collection'
import {
  collectionPage,
  collectionAdd,
  collectionDelete,
  collectionUpdate,
  workstageadd,
  workstagebatchEdit,
  workstageDel,
  collectionShipline,
  collectionLock,
  collectionUnlock,
  collectionTypeList,
  collectionTypeDetail,
  batchUpdate
} from './api/api.js'
import { forSelectText } from '../../utils/index'
import { sorter } from '../../utils/sort'

export default {
  name: 'Collection',
  mixins: [setwarehouse],
  data() {
    return {
      TypeColumns,
      items: items(this),
      modalItems: modalItems(this),
      modalEditItems: modalEditItems(this),
      TypeData: [],
      data: [],
      columns: null,
      remoteUrl: {
        url: '/mock/getTableList',
        headers: {
          'Content-Type': 'application/JSON'
        },
        params: {}
      },
      visibleType: false,
      SetTypevisible: false,
      visible: false,
      loading: false,
      confirmLoading: false,
      actionType: true,
      actionType1: true,
      visibleEditType: false,
      confirmEditLoading: false,
      warehouseCode: '',
      record: {},
      record1: {},
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      shiplineList: [],
      typeList: [],
      selectedRowKeys: []
    }
  },
  created() {
    this.columns = sorter(columns)
    forSelectText([columns], this).then(res => {
      this.columns = res[0]
    })
    // collectionShipline().then(res => {
    //   if (!res.success || !res.data) return;
    //   this.shiplineList = res.data.map(t => ({
    //     shiplineId: t.dictId,
    //     shiplineCode: t.dictCode,
    //     shiplineName: t.dictName,
    //   }));
    //   let options = res.data.map(t => ({
    //     label: t.dictName,
    //     value: t.dictId
    //   }));
    //   this.modalItems.find(t => t.name == 'shiplineId').options.splice(0,0,...options);
    //   this.items.find(t => t.name == 'shiplineId').options.splice(0,0,...options);
    // });
  },
  mounted() {
    this.hanlderSubmit(null, this.$refs.search.form)
    setTimeout(() => {
      let vals = this.$refs.search.form.getFieldsValue()
      let item = this.items.find(t => t.name == 'stageType')
      this.getTypeList(vals.warehouseId, item, true)
      this.getShipline(vals.warehouseCode, this.items)
    }, 1000)
  },
  methods: {
    SetType() {
      this.SetTypevisible = true
    },
    lock() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请勾选项')
        return
      }
      collectionLock(this.selectedRowKeys).then(res => {
        this.getData()
      })
    },
    unlock() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请勾选项')
        return
      }
      collectionUnlock(this.selectedRowKeys).then(res => {
        this.getData()
      })
    },
    batchEdit(){
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请勾选项')
        return
      }
      this.visibleEditType = true
      setTimeout(() => {
        let editVals = this.$refs.modelEditType.form.getFieldsValue()
        let editItem = this.modalEditItems.find(t => t.name == 'stageType')
        this.getTypeList(editVals.warehouseId, editItem, true)
        this.getShipline(this.warehouseCode, this.modalEditItems)
      }, 1000)

    },
    getTypeList(warehouseId, item, isLabel) {
      return collectionTypeList({ warehouseId: warehouseId }).then(res => {
        if (!res.success || !res.data) return
        item.options.splice(
          0,
          item.options.length,
          ...res.data.map(t => ({
            label: t.type,
            value: !!isLabel ? t.type : t.id
          }))
        )
      })
    },
    async getShipline(warehouseCode, item) {
      let data = { warehouseCode }
      this.warehouseCode = warehouseCode
      let res = await collectionShipline(data)
      if (!res.success || !res.data) return
      this.shiplineList = res.data.map(t => ({
        shiplineId: t.shiplineId,
        shiplineCode: t.segment1,
        shiplineName: t.segment2
      }))
      let options = res.data.map(t => ({
        label: t.segment2,
        value: t.shiplineId
      }))
      let p = item.find(t => t.name == 'shiplineId');
      p.options.splice(0, p.options.length, ...options)
      //   this.items.find(t => t.name == 'shiplineId').options.splice(0, 0, ...options)
    },
    getData(p) {
      if (p)
        Object.keys(p).forEach(k => {
          if (!p[k]) p[k] = null
        })
      let params = {
        num: '579657514140962816',
        pageNum: this.pagination.current, // 当前页码
        pageSize: this.pagination.pageSize, // 每页数量
        params: p || {}
      }
      this.loading = true
      collectionPage(params).then(res => {
        this.loading = false
        if (res.success) {
          if (res.data) {
            this.selectedRowKeys = []
            this.data = res.data.list
            this.pagination.total = Number(res.data.totalCount)
          } else {
            this.data = []
            this.pagination = {
              total: 0,
              pageSize: 10, //每页中显示10条数据
              current: 1,
              showSizeChanger: true,
              pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
              showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
            }
          }
        } else {
          this.$exception(res)
        }
      })
    },
    hanlderSubmit(event, form) {
      if (event) event.preventDefault()
      this.getData(form.getFieldsValue())
    },
    hanlderSubmitType(event, form) {
      event.preventDefault()
      this.$refs[this.TypeColumns.ref].reload({ params: form.getFieldsValue() })
    },
    showModal(bool, record) {
      let vals = this.$refs.search.form.getFieldsValue()
      this.visible = true
      this.actionType = bool

      this.$nextTick(() => {
        const { form } = this.$refs.modelForm
        form.resetFields()
        if (bool) {
          let item = this.modalItems.find(t => t.name == 'stageType')
          let modalItem = this.modalItems.find(t => t.name == 'shiplineId');
          item.options.splice(0, item.options.length)
          modalItem.options.splice(0, modalItem.options.length)
        } else {
          this.record = record
          record.isEnable = record.isEnable == 1 ? true : false
          form.setFieldsValue(record)
          let item = this.modalItems.find(t => t.name == 'stageType')
          this.getTypeList(record.warehouseId, item, true)
          this.getShipline(vals.warehouseCode, this.modalItems)
        }
      })
    },
    showModalType(bool, record) {
      this.visibleType = true
      this.actionType1 = bool
      this.$nextTick(() => {
        const { form } = this.$refs.modelFormType
        if (bool) {
          form.resetFields()
        } else {
          this.record1 = record
          form.setFieldsValue(record)
        }
      })
    },
    delSingle(record) {
      this.loading = true
      collectionDelete({ ids: record.stageId }).then(res => {
        if (res.success) {
          this.visible = false
          this.$message.success(res.message || '操作成功')
          this.getData()
        } else {
          //   this.$message.warning(res.message || '操作失败')
          this.$exception(res)
        }
        this.loading = false
      })
    },
    async delSingleType(record) {
      //   this.loading = true
      let res = await workstageDel({ id: record.id })
      if (res.success) {
        this.visibleType = false
        this.$message.success(res.message || '操作成功')
        this.$refs[this.TypeColumns.ref].reload()
      } else {
        // this.$message.warning(res.message || '操作失败')
        this.$exception(res)
      }
      //   collectionDelete({ ids: record.stageId }).then(res => {
      //     if (res.success) {
      //       this.visible = false
      //       this.$message.success(res.message || '操作成功')
      //       this.getData()
      //     } else {
      //       this.$message.warning(res.message || '操作失败')
      //     }
      //     this.loading = false
      //   })
    },
    handleOkType() {
      this.confirmLoading = true
      const { actionType1, record1 } = this
      this.$refs.modelFormType.form.validateFields(async (error, values) => {
        if (!error) {
          //   const res = await workstageadd(values)
          const res = actionType1
            ? await workstageadd(values)
            : await workstagebatchEdit([
                {
                  ...values,
                  id: record1.id
                }
              ])
          //   let msg = res.message
          //   if (res.success) {
          this.visibleType = false
          this.$refs[this.TypeColumns.ref].reload()
          //     this.$message.success(msg || '操作成功')
          //   } else {
          //     this.$message.warning(msg || '操作失败')
          //   }
          //   this.getData()
        }
        this.confirmLoading = false
      })
    },
    handleOkEditType(){
      this.confirmEditLoading = true
      this.$refs.modelEditType.form.validateFields((error, values) => {
        if (!error) {
          const params = []
          this.selectedRowKeys.forEach(item =>{
            params.push({
              ...values,
              stageId: item
            })
          })
          batchUpdate(params).then(res=>{
            let msg = res.data
            if (res.success) {
              this.visibleEditType = false
              this.$message.success(msg || '操作成功')
            } else {
              // this.$message.warning(msg || '操作失败')
              this.$exception(res)
            }

            this.getData()
          })
        }
        this.confirmEditLoading = false
      })
    },
    handleOk(e) {
      this.confirmLoading = true
      const { actionType, record } = this
      this.$refs.modelForm.form.validateFields(async (error, values) => {
        console.log(values)
        if (!error) {
          values.isEnable = values.isEnable ? 1 : 0
          const res = actionType
            ? await collectionAdd(values)
            : await collectionUpdate({
                ...values,
                stageId: record.stageId
              })
          let msg = res.message
          if (res.success) {
            this.visible = false
            this.$message.success(msg || '操作成功')
          } else {
            // this.$message.warning(msg || '操作失败')
            this.$exception(res)
          }

          this.getData()
        }
        this.confirmLoading = false
      })
    },
    handleCancel(e) {
      this.visible = false
    },
    clickRow(selectedRowKeys, record, row) {
      this.$refs.extendForm.form.setFieldsValue(row)
    },
    paginationChange(pagination) {
      this.pagination = pagination
      this.pagination.pageNum = pagination.current
      const params = this.$refs.search.form.getFieldsValue()
      this.getData(params)
    },
    handleCancelTypeVisible() {
      this.SetTypevisible = false
      const params = this.$refs.search.form.getFieldsValue()
      this.getData(params)
    },
    showDetail(record) {
      if (!record || !record.stageCode) {
        this.$message.warning('集货区编号不存在')
        return
      }
      collectionTypeDetail({ stageCode: record.stageCode }).then(res => {
        if (!res.success || !res.data) {
          this.$exception(res)
          return
        }
        // let
        this.$info({
          content: (
            <div style="padding-left:25px;">
              <div>客户数: 0</div>
              <div>订单数: 0</div>
              <div>总数量: 0</div>
            </div>
          )
          // onOk() {},
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.card-custom-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
