<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="物料编码" :labelCol="{span: 6}" :wrapperCol="{span: 14, offset: 1}">
              <a-input option-filter-prop="children" placeholder="请输入物料编码" v-model="queryParam.pno"></a-input>
            </a-form-item>
          </a-col>
<!--          <a-col :md="6" :sm="8">-->
<!--            <a-form-item label="设计人员" :labelCol="{span: 6}" :wrapperCol="{span: 14, offset: 1}">-->
<!--              <a-input placeholder="请输入设计人员姓名" v-model="queryParam.projectName"></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="6" :sm="8">-->
<!--            <a-form-item label="发布人员" :labelCol="{span: 6}" :wrapperCol="{span: 14, offset: 1}">-->
<!--              <a-input placeholder="请输入发布人员姓名" v-model="queryParam.orderNo"></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="queryPBom" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <div>

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
       BOM-物料信息
      </div>

      <a-table
        :columns="columns"
        :scroll="{x: 1500}"
        size="middle"
        :dataSource="bomSource"
        :pagination="false"
        :loading="pbomLoading"
        :expandedRowKeys="expandedRowKeys"
        :customRow="clickThenSelect"
        @expandedRowsChange="handleExpandedRowsChange">

<!--        <span slot="action" slot-scope="text, record">-->
<!--          <a @click="handleEdit(record)">编辑</a>-->
<!--        </span>-->
<!--        &lt;!&ndash; 字符串超长截取省略号显示 &ndash;&gt;-->
<!--        <span slot="url" slot-scope="text">-->
<!--          <j-ellipsis :value="text" :length="25" />-->
<!--        </span>-->
<!--        &lt;!&ndash; 字符串超长截取省略号显示&ndash;&gt;-->
<!--        <span slot="component" slot-scope="text">-->
<!--          <j-ellipsis :value="text" />-->
<!--        </span>-->
      </a-table>



      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        工艺信息
      </div>

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="planColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, onSelectAll: onSelectAll, onSelect: onSelect}"
        @change="handleTableChange">

        <span slot="status" slot-scope="status">
          <a-tag :key="status" :color="solutionPurchaseColor(status)">
            {{ solutionPurchaseStatus(status) }}
          </a-tag>
        </span>

        <span slot="flag" slot-scope="flag">
          <a-tag :key="flag" :color="longTermColor(flag)">
            {{ longTerm(flag) }}
          </a-tag>
        </span>

        <span slot="tradeTime" slot-scope="time">
          {{ timeFormat(time) }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">变更计划时间</a>
          <a-divider type="vertical" />
<!--          <a @click="merge(record)">合并</a>-->
        </span>
      </a-table>

    </div>
    <!-- table区域-end -->
    <purchase-in-modal ref="modalForm" @ok="modalFormOk"></purchase-in-modal>
    <purchase-in-batch-modal ref="batchModalForm"></purchase-in-batch-modal>
    <merge-modal ref="mergeModal"></merge-modal>
    <purchase-in-print-modal ref="purchaseInPrintModal"></purchase-in-print-modal>
  </a-card>


</template>

<script>
import { JeecgListMixin } from '../../mixins/JeecgListMixin'
import {
  queryPBom2,queryProcess
} from '../../api/api'
import moment from 'moment'

const columns = [
  {
    title: '物料编码',
    dataIndex: 'pno',
    key: 'pno'
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '图号',
    dataIndex: 'f08',
    key: 'f08'
  },{
    title: '物料单位',
    dataIndex: 'f02',
    key: 'f02'
  }, {
    title: '用量',
    dataIndex: 'bnum',
    key: 'bnum'
  }, {
    title: '制造方式',
    dataIndex: 'f04',
    key: 'f04'
  },{
    title: 'WIP属性',
    dataIndex: 'f05',
    key: 'f05'
  },{
    title: '分类',
    dataIndex: 'f11',
    key: 'f11'
  }
]
export default {
  name: 'PlmInfo',
  mixins: [JeecgListMixin],
  components: {

  },
  data() {
    return {
      disableMixinCreated: true,
      ids: '',
      printVisible: false,
      confirmLoading: false,
      pbomLoading: false,
      description: '这是采购入库页面',
      defaultValue: 0,
      purchasedStatusList: [],
      bomSource: [],
      // 表头
      columns: columns,
      loading: false,
      // 展开的行,受控属性
      expandedRowKeys: [],
      printDataSource: [],
      printLoading: false,
      queryParam: [],
      projectNameList: [],
      workNoList: [],
      projectNoList: [],
      statusList:[],
      pagination: {
        defaultPageSize: 5,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (current, pageSize) => this.pageSize = pageSize
      },
      bomIdList: [],
      batchForm: this.$form.createForm(this),
      planColumns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name'
        }, {
          title: '工艺',
          dataIndex: 'processName',
          key: 'processName'
        }, {
          title: '准备工时(分钟)',
          dataIndex: 'readyTime',
          key: 'readyTime'
        }, {
          title: '操作工时(分钟)',
          dataIndex: 'completetime',
          key: 'completetime'
        }
      ],
      url: {
        list: '/material/purchase/list',
        importExcelUrl: '/material/purchase/importExcel',
      }
    }
  },
  created() {
    this.loadFrom()
    this.getPurchaseStatus()
  },
  methods: {
    loadFrom() {

    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },

    queryPBom(){
      this.pbomLoading = true
      let params = {
        'pno': this.queryParam.pno,
      }
      queryPBom2(params).then((res) => {
        if (res.success) {
          this.pbomLoading = false
          this.loadData(res.result)
        }else{
          this.pbomLoading = false
          this.bomSource =[];
          this.$message.error("不存在物料信息")
        }
      })

    },

    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChangeByBoom(record.no,record.pbompkgid);
          }
        }
      }
    },

    onSelectChangeByBoom(selectedRowKeys,pbompkgid) {
      this.loading = true
      let params2 = {
        'no': selectedRowKeys,
        'pbompkgid': pbompkgid
      }
      queryProcess(params2).then((res) => {

        if (res.success) {
          this.loading = false
          this.dataSource=res.result.records;
        }else{
          this.loading = false
        }
      })
    },

    loadData(tree) {
      this.bomSource = tree;
    },
    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
    },
    handleBomChange(value) {
      this.initBomTree(value)
    },
    onSelectAll(selected) {
      if (selected) {
        const tabData = this.bomSource;
        const arr = [];
        setVal(tabData, arr);
        this.selectedRowKeys = arr;
      } else {
        this.selectedRowKeys = [];
      }
      function setVal(list, arr) {
        list.forEach(v => {
          arr.push(v.key);
          if (v.children) {
            setVal(v.children, arr);
          }
        });
      }
    },
    onSelect(record, selected) {
      const set = new Set(this.selectedRowKeys);
      const tabData = this.bomSource;
      const key = record.key;
      if (selected) {
        set.add(key);
        record.children && setChildCheck(record.children);
        // setParentCheck(key);
      } else {
        set.delete(key);
        record.children && setChildUncheck(record.children);
        setParentUncheck(key);
      }

      this.selectedRowKeys = Array.from(set);
      // 设置父级选择
      function setParentCheck(key) {
        let parent = getParent(key);
        if (parent) {
          set.add(parent.key);
          setParentCheck(parent.key);
        }
      }
      // 设置父级取消,如果父级的子集有选择,则不取消
      function setParentUncheck(key) {
        let childHasCheck = false,
          parent = getParent(key);
        if (parent) {
          let childlist = parent.children;
          childlist.forEach(function(v) {
            if (set.has(v.key)) {
              childHasCheck = true;
            }
          });
          if (!childHasCheck) {
            set.delete(parent.key);
            setParentUncheck(parent.key);
          }
        }
      }
      // 获取当前对象的父级
      function getParent(key) {
        for (let i = 0; i < tabData.length; i++) {
          if (tabData[i].key === key) {
            return null;
          }
        }
        return _getParent(tabData);
        function _getParent(list) {
          let childlist,
            isExist = false;
          for (let i = 0; i < list.length; i++) {
            if ((childlist = list[i].children)) {
              childlist.forEach(function(v) {
                if (v.key === key) {
                  isExist = true;
                }
              });
              if (isExist) {
                return list[i];
              }
              if (_getParent(childlist)) {
                return _getParent(childlist);
              }
            }
          }
        }
      }
      // 设置child全选
      function setChildCheck(list) {
        list.forEach(function(v) {
          set.add(v.key);
          v.children && setChildCheck(v.children);
        });
      }
      // 设置child取消
      function setChildUncheck(list) {
        list.forEach(function(v) {
          set.delete(v.key);
          v.children && setChildUncheck(v.children);
        });
      }
    },

    /** 点击a-table中的行后,展开或关闭其子行 */
    tableClick(record, index){
      return {
        style:{
          cursor:'pointer',
        },
        on: {
          click: () => {
            this.expandRowByClick = !this.expandRowByClick;
          }
        }
      }
    },
    query() {
      this.pbomLoading = true
      this.loading = true
      let params = {
        'bomId': this.queryParam.bomId,
        'projectName': this.queryParam.projectName,
        'projectNo': this.queryParam.projectNo,
        'workNo': this.queryParam.workNo
      }
      getBomId(params).then((res) => {
        this.bomIdList = []
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            this.bomIdList.push(res.result[i])
          }
          this.initBomTree(this.bomIdList[0])
        } else {
          this.$message.warning(res.message)
          this.loading = false
          this.pbomLoading = false
        }
      })
    },



    print() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录!')
        return "";
      }
      this.$refs.purchaseInPrintModal.open(this.selectedRowKeys)
    },
    handleCancel(e) {
      this.printVisible = false
    },
    getPurchaseStatus() {
      ajaxGetDictItems('purchased_status').then((res) => {
        if (res.success) {
          this.purchasedStatusList = res.result
        }
      })
    },
    solutionPurchaseStatus(value) {
      var actions = []
      Object.keys(this.purchasedStatusList).some((key) => {
        if (this.purchasedStatusList[key].value == ('' + value)) {
          actions.push(this.purchasedStatusList[key].text)
          return true
        }
      })
      return actions.join('')
    },
    solutionPurchaseColor(value) {
      var actions = ''
      Object.keys(this.purchasedStatusList).some((key) => {
        if (this.purchasedStatusList[key].value == ('' + value)) {
          actions = this.purchasedStatusList[key].color
        }
      })
      return actions
    },
    longTerm(flag) {
      if (flag == '0') {
        return "否"
      } else {
        return "是"
      }
    },
    longTermColor(flag) {
      if (flag == '0') {
        return "volcano"
      } else {
        return "blue"
      }
    },
    timeFormat(val) {
      if(val==undefined){
        return "";
      }else{
        return moment(val).format('YYYY-MM-DD')
      }
    },
    merge(record) {
      this.$refs.mergeModal.open(record)
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  }
}
</script>

<style scoped>

</style>