<template>
  <div class="add_reservoir">
    <!-- 新增弹出 -->
    <add_reservoir
      :visible.sync="visible"
      :rows.sync="rows"
      :warehouse_page="warehouse_page"
      :baseWmsWarehouseRoomMst_page="baseWmsWarehouseRoomMst_page"
      @handleAdd="handleAdd"
    />

    <p-card title="库区定义">
      <span slot="extra">
        <p-button type="primary" icon="plus" style="margin-right: 1rem;" @click="showModal({})">新增</p-button>
        <p-button type="primary" icon="delete" @click="delIds">批量删除</p-button>
      </span>
      <p-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" :form="form" ref="search" @submit="handleSubmit">
        <a-row>
          <a-col :span="8">
            <p-form-item label="仓库名称">
              <!--查询 隐藏的仓库id -->
              <p-input type="hidden" v-decorator="['warehouseId']" />
              <!--查询 隐藏的仓库编码 -->
              <p-input type="hidden" v-decorator="['warehouseCode']" />
              <p-search-modal
                title="仓库名称"
                v-decorator="[
                  'warehouseName',
                  { initialValue: warehouse.warehouseName },
                  { rules: [{ required: false, message: '请输入！' }] }
                ]"
                :target-click="true"
                :remoteUrl="{
                  url: '/api/upcloud-base-wh/warehouse/page',
                  method: 'get'
                }"
                rowSelectType="radio"
                targetValueKey="warehouseName"
                rowKey="warehouseId"
                :tableConfig="{
                  columns: [
                    { dataIndex: 'warehouseName', title: '仓库名称' },
                    { dataIndex: 'warehouseCode', title: '仓库编码' },
                    { dataIndex: 'warehouseType', title: '仓库类型' },
                    { dataIndex: 'dcName', title: '所属仓配中心' }
                  ]
                }"
                :toolBar="{
                  items: [
                    { type: 'input', name: 'warehouseName', label: '仓库名称', value: '' },
                    { type: 'input', name: 'warehouseCode', label: '仓库编码', value: '' }
                  ]
                }"
                @ok="setWarehouseCode"
                @change="clearWarehouseCode"
              />
            </p-form-item>
          </a-col>
          <a-col :span="8">
            <!-- <p-form-item label="建筑物名称">
					  <p-input allow-clear
					  v-decorator="['bldgCode', { rules: [{ required: false, message: '请输入！' }] }]"
					  />
				</p-form-item> -->
            <p-form-item label="库区名称">
              <p-input
                allow-clear
                v-decorator="['warehouseAreaName', { rules: [{ required: false, message: '请输入！' }] }]"
              />
            </p-form-item>
          </a-col>
          <a-col :span="8">
            <p-form-item label="库区编码">
              <p-input
                allow-clear
                v-decorator="['warehouseAreaCode', { rules: [{ required: false, message: '请输入！' }] }]"
              />
            </p-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <p-form-item label="是否启用">
              <p-select
                v-decorator="['isEnable', { rules: [{ required: false, message: '请输入！' }] }]"
                style=""
                :options="[
                  { title: '全部', value: '' },
                  { title: '禁用', value: '0' },
                  { title: '启用', value: '1' }
                ]"
              />
            </p-form-item>
          </a-col>
          <a-col :span="8" style="text-align: center;">
            <p-form-item>
              <p-button type="primary" icon="search" html-type="submit">查询</p-button>
              <p-button type="" icon="undo" @click="handleReset" style="margin-left: 1rem;">重置</p-button>
            </p-form-item>
          </a-col>
        </a-row>
      </p-form>
      <p-spin :spinning="spinning" style="margin-top: 16px;">
        <p-table
          dragle
		  auto-width
		  :scroll="{x:true}"
          :columns="columns"
          :data-source="data"
          rowKey="warehouseAreaId"
          :loading="loading"
          @checkRow="checkRow"
          @change="changePagination"
          :pagination="pagination"
          bordered
        >
          <!--<template slot="warehouseRoomId" slot-scope="text,row,index">
					{{ returnWarehouseRoomId(text) }}
				</template>	 
				 <template slot="warehouseId" slot-scope="text,row,index">
					{{ returnWarehouseName(text) }}
				</template> -->
          <template slot="isEnable" slot-scope="text, row, index">
            {{ text == '1' ? '启用' : '禁用' }}
          </template>
          <!-- 拣货方式 -->
          <template slot="pickMode" slot-scope="text, row, index">
            {{ returnPickMode(text) }}
          </template>
          <!-- 库区类型 -->
          <template slot="warehouseAreaType" slot-scope="text, row, index">
            {{ returnWarehouseAreaType(text) }}
          </template>
          <span slot="action" slot-scope="text, record, index">
            <a @click="showModal(record)">编辑</a>
            <a-divider type="vertical" style="" />
            <a @click="del(record.warehouseId)">删除</a>
          </span>
        </p-table>
      </p-spin>
    </p-card>
  </div>
</template>

<script>
import moment from 'moment'
import add_reservoir from './components/add_reservoir.vue'
import { dict_listbytype } from '../api/api_warehouse.js'
import {
  baseWmsWarehouseArea_page,
  baseWmsWarehouseArea_page2,
  baseWmsWarehouseArea_add,
  baseWmsWarehouseArea_edit,
  baseWmsWarehouseArea_delete,
  baseWmsWarehouseArea_delByWarehouseId,
  warehouse_page,
  baseWmsWarehouseRoomMst_page
} from '../api/api_warehouse.js'

const columns = [
  { dataIndex: 'warehouseAreaCode', title: '库区编码', scopedSlots: { customRender: 'warehouseAreaCode' }, width: 80 },
  { dataIndex: 'warehouseAreaName', title: '库区名称', scopedSlots: { customRender: 'warehouseAreaName' }, width: 80 },
  { dataIndex: 'warehouseAreaType', title: '库区类型', scopedSlots: { customRender: 'warehouseAreaType' }, width: 80 },
  { dataIndex: 'warehouseName', title: '仓库名称', scopedSlots: { customRender: 'warehouseId' }, width: 80 },
  { dataIndex: 'bldgName', title: '建筑物名称', width: 80, scopedSlots: { customRender: 'bldgName' } },
  { dataIndex: 'warehouseRoomName', title: '库房名称', scopedSlots: { customRender: 'warehouseRoomId' }, width: 80 },
  { dataIndex: 'pickMode', title: '拣货方式', scopedSlots: { customRender: 'pickMode' }, width: 80 },
  { dataIndex: 'splitGroup', title: '拆零分组', scopedSlots: { customRender: 'splitGroup' }, width: 80 },
  { dataIndex: 'cell01', title: '暂存区', scopedSlots: { customRender: 'splitGroup' }, width: 80 },
  /* {dataIndex: 'dcId', title: '冗余字段',scopedSlots: { customRender: 'dcId' },width:80,}, */
  { dataIndex: 'floorNum', title: '所在楼层', scopedSlots: { customRender: 'floorNum' }, width: 80 },
  {
    dataIndex: 'warehouseAreaDistance',
    title: '作业距离(米)',
    scopedSlots: { customRender: 'warehouseAreaDistance' },
    width: 80
  },
  { dataIndex: 'isEnable', title: '是否启用', scopedSlots: { customRender: 'isEnable' }, width: 80 },
  /* {dataIndex: 'accessLevel', title: '数据访问控制级别',scopedSlots: { customRender: 'accessLevel' },width:80,}, */
  { dataIndex: 'creatorName', title: '创建人', scopedSlots: { customRender: 'creator' }, width: 80 },
  { dataIndex: 'modifierName', title: '最后修改人', scopedSlots: { customRender: 'modifier' }, width: 80 },
  { dataIndex: 'gmtCreate', title: '创建日期', scopedSlots: { customRender: 'gmtCreate' }, width: 80 },
  { dataIndex: 'gmtModified', title: '最后修改日期', scopedSlots: { customRender: 'gmtModified' }, width: 80 },
  { dataIndex: 'attribute1', title: '预留字段1', scopedSlots: { customRender: 'attribute1' }, width: 80 },
  { dataIndex: 'attribute2', title: '预留字段2', scopedSlots: { customRender: 'attribute2' }, width: 80 },
  { dataIndex: 'attribute3', title: '预留字段3', scopedSlots: { customRender: 'attribute3' }, width: 80 },
  { dataIndex: 'attribute4', title: '预留字段4', scopedSlots: { customRender: 'attribute4' }, width: 80 },
  { dataIndex: 'attribute5', title: '预留字段5', scopedSlots: { customRender: 'attribute5' }, width: 80 },
  { dataIndex: 'segment1', title: '预留字段6', scopedSlots: { customRender: 'segment1' }, width: 80 },
  { dataIndex: 'segment2', title: '预留字段7', scopedSlots: { customRender: 'segment2' }, width: 80 },
  { dataIndex: 'segment3', title: '预留字段8', scopedSlots: { customRender: 'segment3' }, width: 80 },
  { dataIndex: 'segment4', title: '预留字段9', scopedSlots: { customRender: 'segment4' }, width: 80 },
  { dataIndex: 'segment10', title: '预留字段10', scopedSlots: { customRender: 'segment10' }, width: 80 },
  {
    dataIndex: 'action',
    title: '操作',
    scopedSlots: { customRender: 'action' },
    width: 90,
    fixed: 'right',
    align: 'center'
  }
]
export default {
  components: { add_reservoir },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'horizontal_login' }),
      columns,
      rows: {},
      data: [],
      visible: false,
      spinning: false,
      ids: '',
      pickMode: [], //拣货方式
      warehouseAreaType: [], //库区类型
      warehouse: this.$store.state.user.warehouse, //vuex库房共享资料
      baseWmsWarehouseRoomMst_page: [], //库房
      warehouse_page: [], //仓库
      loading: false,
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      }
    }
  }, //data
  methods: {
    // 查询仓库时设置仓库代码
    setWarehouseCode(event, selectId, selectData) {
      this.$refs.search.form.setFieldsValue({
        warehouseCode: selectData[0].warehouseCode, //仓库代码
        warehouseId: selectData[0].warehouseId //仓库代码
      })
    },
    // 清除查询仓库时设置仓库代码
    clearWarehouseCode(event, selectId, selectData) {
      if (!selectId) {
        this.$refs.search.form.setFieldsValue({
          warehouseCode: '', //仓库代码
          warehouseId: '',
          warehouseName: ''
        })
      }
    },
    showModal(rows) {
      this.visible = true
      rows = { ...rows }
      if (rows.warehouseAreaId) {
        this.rows = Object.assign(rows, { id: '编辑id', isEnable: rows.isEnable == '1' ? true : false })
      } else {
        this.rows = { isEnable: true }
      }
    },
    getData(params) {
      params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...params
      }
      this.loading = true
      baseWmsWarehouseArea_page2(params).then(res => {
        if (res.success) {
          this.data = res.data.list
          this.pagination.total = Number(res.data.totalCount)
          this.loading = false
        } else {
          this.loading = false
          this.$exception(res)
        }
      })
    },

    changePagination(pagination, filters, sorter) {
      // 分页变化
      this.pagination = pagination
      this.getData() //分页查询所有列表
    },
    // 查询
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.getData(values)
        }
      })
    },
    handleReset() {
      this.form.resetFields()
      this.$refs.search.form.setFieldsValue({
        warehouseName: '' //仓库名称
      })
    },
    // 选择时的变化, 必须点到 checkbox 上或者'hasRowSelectCheck=true'点击行
    checkRow(selectedRowKeys, selectedRows) {
      this.ids = selectedRows.map(item => item.warehouseAreaId).join()
      // selectedRowKeys.toString();
    },

    // 批量删除
    delIds() {
      let _this = this
      if (this.ids) {
        this.$confirm({
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            baseWmsWarehouseArea_delete({ ids: _this.ids }).then(res => {
              if (res.success) {
                _this.$message.success(`批量删除成功！${res.message}`)
                _this.getData({}) //分页查询所有列表
              } else {
                _this.$message.error(`删除失败！${res.message}`)
              }
            })
          }
        })
      } else {
        this.$message.warning('请选择要删除记录')
      }
    },
    // 根据库存id删除一条
    del(id) {
      let _this = this
      this.$confirm({
        title: '是否删除?',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          baseWmsWarehouseArea_delByWarehouseId({ id: id }).then(res => {
            if (res.success) {
              _this.$message.success(`删除成功！${res.message}`)
              _this.getData({}) //分页查询所有列表
            } else {
              _this.$message.error(`删除失败！${res.message}`)
            }
          })
        }
      })
    },

    // 新增 / 修改
    handleAdd(rows) {
      if (this.rows.id) {
        // id存在,则进入编辑状态。
        baseWmsWarehouseArea_edit(rows).then(res => {
          if (res.success) {
            this.visible = false
            this.$message.success(`编辑成功！${res.message}`)
            this.getData({}) //分页查询所有列表
          } else {
            // this.$message.error(`编辑失败！${res.message}`);
            this.$exception(res)
          }
        })
      } else {
        /* let params = Object.assign(rows,{		isEnable:rows.isEnable?'1':'0',
													"enterpriseId":"01",	//企业ID
													"gmtCreate":moment().format('YYYY-MM-DD HH:mm:ss'),
													"gmtModified":moment().format('YYYY-MM-DD HH:mm:ss'),
													"creator":this.$store.state.user.info.nickname,
													"modifier":this.$store.state.user.info.nickname,
													"modifierName":this.$store.state.user.info.nickname,
													"creatorName":this.$store.state.user.info.nickname
												}); */
        if (this.data.find(item => item.warehouseAreaCode == rows.warehouseAreaCode)) {
          this.$message.warning('库区编码已存在')
        } else {
          baseWmsWarehouseArea_add(rows).then(res => {
            if (res.success) {
              this.visible = false
              this.$message.success(`新增成功！${res.message}`)
              this.getData({}) //分页查询所有列表
            } else {
              // this.$message.error(`新增失败！${res.message}`);
              this.$exception(res)
            }
          })
        }
      }
    },
    // 库区主表 分页查询
    /* baseWmsWarehouseArea_page(params){
		this.spinning =true;
		baseWmsWarehouseArea_page2(params).then(res=>{
			if(res.success){
				this.data = res.data;
				this.spinning = false;
			} else {
				this.spinning =false;
				this.$exception(res);
			}
		})
	}, */
    // 过滤仓库id为名称
    returnWarehouseName(text) {
      let temp = this.warehouse_page.find(v => v.value == text)
      return temp ? temp.title : text
    },
    // 过滤库房id为名称
    returnWarehouseRoomId(text) {
      let temp = this.baseWmsWarehouseRoomMst_page.find(v => v.value == text)
      return temp ? temp.title : text
    },
    //过滤拣货方式
    returnPickMode(text) {
      let temp = this.pickMode.find(v => v.dictCode == text)
      return temp ? temp.dictName : text
    },
    //过滤库区类型
    returnWarehouseAreaType(text) {
      let temp = this.warehouseAreaType.find(v => v.dictCode == text)
      return temp ? temp.dictName : text
    }
  }, //methods
  created() {
    //  数据字典：拣货方式
    dict_listbytype({ dicttypeCodes: 'wms_pickmode' }).then(res => {
      if (res.success) {
        this.pickMode = res.data
      }
    })
    // 数据字典：库区类型
    dict_listbytype({ dicttypeCodes: 'areatype' }).then(res => {
      if (res.success) {
        this.warehouseAreaType = res.data
      }
    })
  },
  mounted() {
    // 库区查询
    this.getData({})
    this.$refs.search.form.setFieldsValue({
      warehouseCode: this.warehouse.warehouseCode, //仓库代码
      warehouseId: this.warehouse.warehouseId //仓库id
    })
    // 所属仓库
    /* warehouse_page({pageNum:1,pageSize:100}).then(res=>{
			if(res.success){
				this.warehouse_page = res.data.list.map(item=>{
					return {
						title:item.warehouseName,
						value:item.warehouseId,
					}
				})
			}
		}); */
    // 库房
    /* baseWmsWarehouseRoomMst_page({}).then(res=>{
			if(res.success){
				// this.data = res.data;
				this.baseWmsWarehouseRoomMst_page = res.data.map(item=>{
					return {
						title:item.warehouseRoomName,
						value:item.warehouseRoomId,
					}
				})
			} 
		}); */
  }
}
</script>

<style scoped lang="less">
::v-deep {
  .ant-card-body {
    text-align: left;
  }
  .ant-card-head-title {
    text-align: left;
  }
  .ant-form-inline .ant-form-item {
    margin-right: 2rem;
  }
}
</style>
