<!-- 物料选择组件 -->
<template>
    <div class="container">
      <div class="title" style="display: flex;align-items: center;justify-content: space-between">
        <div style="flex: 1;"></div>
        <div style="flex: 1;">修改人工盘点</div>
        <span style="flex: 1;font-size: 12px;font-weight: normal;cursor: pointer;text-align: right;margin-right: 20px" @click="back">
          <Icon type="ios-arrow-dropleft" size="16"/>
          返回上一级
        </span>
      </div>
      <div class="row">
        <div class="label">盘点人：</div>
        <Select v-model="userId" clearable style="width:200px">
          <Option v-for="item in userList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        <div class="label" style="margin-left: 30px;">盘点时间：</div>
        <DatePicker v-model="taskRunMinTime" format="yyyy-MM-dd HH:mm" type="datetime" placeholder="请选择时间" style="width: 200px"></DatePicker>
      </div>
      <div class="row">
        <div class="label">盘点物料：</div>
      </div>
      <div class="row" style="height: auto;flex-wrap: wrap;">
        <div class="filter-item" v-for="(item, index) in tabs" :key="index">
          <Button
            v-if="item"
            :type="tabIndex === index ? 'primary' : 'default'"
            style="min-width: 90px;margin-bottom: 10px;margin-right: 10px"
            @click="tabClick(index, item.value)">
            {{ item.text }}
          </Button>
        </div>
      </div>
      <div class="row" style="height: auto;flex-wrap: wrap;">
        <div class="filter-item">
          <Button
            :type="itemIndex === '' ? 'primary' : 'default'"
            style="width: 90px;margin-bottom: 10px;margin-right: 10px"
            @click="itemClick()">
            全部
          </Button>
        </div>
        <div class="filter-item" v-for="(item, index) in itemData" :key="index">
          <Button
            v-if="item"
            :type="itemIndex === index ? 'primary' : 'default'"
            style="min-width: 90px;margin-bottom: 10px;margin-right: 10px"
            @click="itemClick(index, item)">
            {{ item }}
          </Button>
        </div>
      </div>
      <div class="content">
        <div class="right">
          <div class="main">
            <my-table
              ref="handleTable"
              :data="data"
              :columns="columns"
              :table-filter="tableFilter"
              :table-page="params"
              :selected-list="handleData"
              :select-key="selectKey"
              :multiple="multiple"
              :show-flag="modal"
              :key="renderKey"
              @on-select="tableSelectChange"
              @on-select-cancel="tableSelectCancel"
              @on-select-all-cancel="allCancel"
              @event-handle="eventHandle"
              @on-change="changePage"
              @on-select-all="selectAll"
            ></my-table>
          </div>
        </div>
        <div class="handle-list">
          <div class="main">
            <my-table
                ref="cfmTable"
                :key="renderKey"
                :data="handleData"
                :columns="columns2"
                :is-show-page="false"
                :is-show-filter="false"
              >
            </my-table>
          </div>
        </div>
      </div>
      <div class="footer">
        <Button type="primary" size="large" @click="cfm">发起盘点</Button>
      </div>
    </div>
</template>

<script>
import {
  GetMaterialPageList, GetTechnologyTypList
} from '@/api/baseData'
import MyTable from '../my-table/my-table'
import MyNumberBoardInput from '../my-number-board-input/my-number-board-input'
import { GetUserList } from '@/api/user'
import { GetStockMaterialPurpose, GetUserCheck, SubmitUserCheck } from '@/api/stock'

export default {
  name: 'material_maintenance',
  components: {
    MyTable,
    MyNumberBoardInput
  },
  watch: {
    value: {
      handler (n) {
        this.modal = n
      },
      immediate: true
    },
    modal (n) {
      this.$emit('input', n)
    },
    treeData: {
      handler (newVal, oldVal) {
        this.initData(this.treeData)
      },
      deep: true
    }
  },
  props: {
    // 已选数据
    selectedList: {
      type: Array,
      default () {
        return []
      }
    },
    /* 数据回填所根据的key */
    selectKey: {
      type: String,
      default: 'code'
    },
    /* 是否单选 */
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否显示表单
    value: {
      type: Boolean,
      default: false,
      require: true
    }
  },
  data () {
    return {
      id: '',
      itemData: [],
      itemIndex: '',
      tabIndex: 0,
      userId: '',
      taskRunMinTime: this.$dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm'),
      userList: [],
      modal: false,
      categoryCode: '',
      tabs: [],
      columns2: [
        {
          title: '物料名称',
          key: 'name',
          minWidth: 150
        },
        {
          title: '操作',
          width: 80,
          align: 'center',
          render: (h, params) => {
            let that = this
            return h('Icon', {
              props: {
                type: 'ios-trash',
                size: 24,
                color: 'red'
              },
              style: {
                cursor: 'pointer'
              },
              on: {
                click (e) {
                  e.stopPropagation()
                  that.handleData.splice(params.row._index, 1)
                  that.renderKey = new Date().getTime()
                  that.$refs.handleTable.handleCancel(params.row.code)
                }
              }
            })
          }
        }
      ],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '物料编码',
          key: 'code',
          width: 120
        },
        {
          title: '物料名称',
          key: 'name',
          minWidth: 150
        },
        {
          title: '物料类型',
          key: 'technologyTypeStr',
          minWidth: 150
        },
        {
          title: '库存',
          key: 'stockQty',
          minWidth: 150
        },
        {
          title: '用途',
          key: 'purpose',
          minWidth: 150
        }
      ],
      tableFilter: [
        {
          name: 'Input',
          value: 'key',
          placeholder: '请输入关键字',
          e: 'change'
        },
        {
          name: 'Button',
          type: 'primary',
          text: '查询',
          e: 'search'
        },
        {
          name: 'Button',
          text: '选择全部',
          e: 'selectAll'
        }
      ],
      params: {
        pageIndex: 1,
        pageSize: 20,
        total: 0,
        technologyType: '',
        categoryCode: this.$store.state.materialCategoryId
      },
      data: [],
      handleData: [],
      checkedList: [],
      renderKey: new Date().getTime()
    }
  },
  methods: {
    back () {
      this.$store.commit('closeTag', this.$route)
      setTimeout(() => {
        this.$router.push('inventory_record')
      }, 500)
    },
    tabClick (index = '', value = '') {
      this.tabIndex = index
      this.itemIndex = ''
      this.params.technologyType = value
      this.params.pageIndex = 1
      this.params.purpose = ''
      this.getItemData()
      this.getList()
    },
    itemClick (index = '', item = '') {
      this.itemIndex = index
      this.params.purpose = item
      this.params.pageIndex = 1
      this.getList()
    },
    cfm () {
      console.log(this.handleData)
      if (!this.id) return this.$Message.error('修改信息为空！')
      if (!this.userId) return this.$Message.error('请选择盘点人！')
      if (!this.taskRunMinTime) return this.$Message.error('请选择盘点时间！')
      if (this.handleData.length < 1) return this.$Message.error('请选择物料！')
      SubmitUserCheck({
        recordId: this.id,
        taskRunMinTime: this.taskRunMinTime,
        userId: this.userId,
        materialCodeList: this.handleData.map(item => item.code)
      }).then(res => {
        if (res.code === 0) {
          this.$Message.info(res.msg || '操作成功')
          this.userId = ''
          this.taskRunMinTime = ''
          this.handleData = []
          this.$refs.handleTable.clear()
          this.$emit('close')
        }
      })
    },
    cancel () {
      this.$refs.table.clear()
      this.modal = false
    },
    getList () {
      GetMaterialPageList({
        ...this.params,
        isNotShowZeroStock: true,
        technologyType: this.params.technologyType
      }).then(res => {
        if (res.code === 0) {
          this.data = res.result.list
          this.params.total = res.result.totalCount
          this.modal = true
        }
      })
    },
    initData (array) {
      array.forEach(item => {
        item.title = item.name
        if (item.children) {
          this.initData(item.children)
        }
      })
    },
    allCancel (data) {
      data.forEach(data => {
        this.handleData.forEach((item, index) => {
          if (data.code === item.code) {
            this.handleData.splice(index, 1)
          }
        })
      })
    },
    // 获取表格选中数据
    tableSelectChange (selection, row) {
      if (this.handleData.length < 1 && row.code) {
        this.handleData.push({ ...row, quantity: 1 })
      } else {
        let isExist = false
        this.handleData.forEach(item => {
          if (item.code === row.code) {
            isExist = true
          }
        })
        if (!isExist && selection.length > 0 && row.code) {
          this.handleData.push({ ...row, quantity: 1 })
        }
      }
    },
    selectAll (selection) {
      selection.forEach(data => {
        let isExist = false
        this.handleData.forEach(item => {
          if (item.code === data.code) {
            isExist = true
          }
        })
        if (!isExist) {
          this.handleData.push({ ...data, quantity: 1 })
        }
      })
    },
    tableSelectCancel (selection, row) {
      console.log('??????????/row')
      console.log(row)
      console.log(selection)
      // if (selection.length < 1) {
      //   this.handleData = []
      // }
      this.handleData.forEach((item, index) => {
        if (item.code === row.code) {
          this.handleData.splice(index, 1)
          // that.$refs.handleTable.handleCancel(item.code)
          // that.$refs.table.handleCancel(item.code)
        }
      })
      console.log('handleData-----')
      console.log(this.handleData)
    },
    changePage (pageIndex) {
      this.params.pageIndex = pageIndex
      this.getList()
    },
    // 检索条件事件处理
    eventHandle (option) {
      switch (option._evnet) {
        case 'search':
          this.params.pageIndex = 1
          this.params.key = option.key
          this.getList()
          break
        case 'change':
          this.params.key = option.key
          break
        case 'selectAll':
          GetMaterialPageList({
            ...this.params,
            isNotShowZeroStock: true,
            technologyType: this.params.technologyType,
            pageIndex: 1,
            pageSize: 9999999
          }).then(res => {
            if (res.code === 0) {
              this.handleData.push(...res.result.list)
            }
          })
          break
      }
    },
    // 选择物料分类 显示物料列表
    treeCheck (data) {
      this.categoryCode = data.value
      this.params.categoryCode = data.value
      this.getList()
    },
    getUserPageList () {
      GetUserList().then(res => {
        if (res.code === 0) {
          let list = res.result.map(item => {
            return {
              label: item.key,
              value: item.value
            }
          })
          this.userList = list
        }
      })
    },
    getItemData () {
      GetStockMaterialPurpose({
        technologyType: this.params.technologyType
      }).then(res => {
        if (res.code === 0) {
          this.itemData = res.result
        }
      })
    },
    /* 获取回填相关信息 */
    getUserCheck () {
      this.modal = false
      GetUserCheck({
        id: this.id
      }).then(res => {
        if (res.code === 0) {
          this.userId = res.result.userId
          this.taskRunMinTime = res.result.taskRunMinTime
          this.handleData = res.result.materialCodeList.map(item => {
            return {
              id: item.key,
              code: item.key,
              name: item.value
            }
          })
          this.getList()
        }
      })
    },
    getTechnologyTypList () {
      GetTechnologyTypList().then(res => {
        if (res.code === 0) {
          this.tabs = res.result
          this.tabs.unshift({
            text: '全部',
            value: ''
          })
        }
      })
    }
  },
  mounted () {
    this.id = this.$route.query.id
    this.getUserCheck()
    this.getUserPageList()
    this.getItemData()
    this.getTechnologyTypList()
  }
}
</script>

<style lang="less" scoped>
  .container {
    background: #FFFFFF;
    padding: 10px 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    .title {
      padding-bottom: 10px;
      font-size: 18px;
      font-weight: bold;
      text-align: center;
      color: #000000;
    }
    .row {
      padding: 0 10px;
      display: flex;
      align-items: center;
      height: 32px;
      line-height: 32px;
      .label {
        width: 60px;
        font-weight: bold;
      }
    }
    .content {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      flex: 1;
      overflow: hidden;
      .left, .right, .handle-list {
        height: 100%;
        overflow: auto;
        box-shadow: 3px 3px 5px rgba(57, 57, 57, 0.8);
        background-color: #FFFFFF;
        border-radius: 5px;
        .main {
          box-sizing: border-box;
          padding: 10px;
          height: 100%;
          overflow: auto
        }
      }
      .right {
        margin-right: 15px;
        flex: 2;
        min-width: 500px;
      }
      .handle-list {
        flex: 1;
        min-width: 400px;
      }
    }
  }
  .footer {
    padding: 10px 0;
    /deep/ .ivu-btn-large {
      font-weight: bold;
      width: 150px;
    }
  }

/deep/ .ivu-tree {
  ul {
    text-align: left;
  }
}
</style>
