<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="4" :sm="8">
            <a-form-item label="工作令">
              <a-input placeholder="请输入工作令" v-model="queryParam.field0056"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="项目名称">
              <a-input placeholder="请输入项目名称" v-model="queryParam.field0047"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="4">
            <a-form-item label="bom是否抓取">
              <a-select style="width: 220px" v-model="queryParam.status" placeholder="请选择状态">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="0">未抓取</a-select-option>
                <a-select-option value="1">已抓取</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="4">
            <a-form-item label="pbom是否发布">
              <a-select style="width: 220px" v-model="queryParam.pbom_status" placeholder="请选择状态">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="2">未发布</a-select-option>
                <a-select-option value="1">已发布</a-select-option>
              </a-select>
            </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="searchQuery" 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 class="right-btns">-->
<!--        &lt;!&ndash; 按钮 &ndash;&gt;-->
<!--        <a-button class="table" @click="handleTable"><a-icon type="table" /></a-button>-->
<!--        &lt;!&ndash; 弹出框 &ndash;&gt;-->
<!--        <div class="tableSelect" v-if="tableSelectVisible">-->
<!--          <a-checkbox-group :value="checkValue" :options="colOptions"/>-->
<!--        </div>-->
<!--      </div>-->

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        class="j-table-force-nowrap"
        :dataSource="dataSource"
        :pagination="ipagination"
        :customRow="clickThenSelect"
        :rowClassName="rowClassName"
        @change="handleTableChange"
        >

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


    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;line-height:2">
      pbom-库存信息

      <span style="float: right;margin-right: 10px;"  >
        <a-button type="primary" @click="sendPbom" icon="rocket">发布pbom</a-button>

      </span>

    </div>

    <a-table
      :scroll="{x: 1500}"
      ref="table"
      size="middle"
      rowKey="id"
      :columns="planColumns"
      :dataSource="bomSource"
      :pagination="false"
      :loading="loading"
      :expandedRowKeys="expandedRowKeys"
      @change="handleTableChange"
      @expand="handleExpand"
      v-bind="tableProps" >


      <span slot="status" slot-scope="status, record">
          <a-tag :key="status" :color="solutionColor(record)">
            {{ confirmHandle(record) }}
          </a-tag>
      </span>

      <span slot="tradeNum" slot-scope="qty">
          {{ numFormat(qty) }}
      </span>

      <span slot="updateF04" slot-scope="text, record">
         <a-popconfirm title="确定编辑制造属性吗?" @confirm="() => updateF04(record)">
            <a>{{record.f04}}</a>
          </a-popconfirm>
      </span>

      <span slot="checkQty" slot-scope="text, record">
            <a @click="checkQty(record)">{{numFormat(record.qty)}}</a>
      </span>

<!--      <span slot="action" slot-scope="action, record">-->
<!--          <a @click="handleEdit(record)">锁定工作令</a>-->
<!--        </span>-->
    </a-table>
    <!-- table区域-end -->
    <pbom-type-form ref="pbomTypeForm" @fatherMethod="fatherMethodOther"></pbom-type-form>
    <pbom-form ref="pbomForm"></pbom-form>
    <materia-item-list ref="materiaFrom"></materia-item-list>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '../../mixins/JeecgListMixin'
import moment from 'moment'
import {ajaxGetDictItems, queryPBomByWms} from "../../api/api";
import { getAction } from '@/api/manage'
import PbomTypeForm from './modules/PbomTypeForm'
import PbomForm from './modules/PbomForm'
import MateriaItemList from "./modules/MateriaItemList";
import '@/assets/less/TableExpand.less'

export default {
  name: 'ProjectBomList',
  components: {PbomTypeForm,PbomForm,MateriaItemList},
  mixins: [JeecgListMixin],
  data() {
    return {
      selectIndex: null,
      queryParam: {},
      description: '项目C表信息',
      // 表头
      url: {
        list: '/pbom/pbom/projectList',
        childList: "/pbom/pbom/childList",
      },
      // 展开的行,受控属性
      expandedRowKeys: [],
      dataSource: [],
      bomSource: [],
      pnoArray:[],
      scolor:'',
      pno:'',
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '50'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      hasChildrenField:"hasChild",
      pidField:"pno",
      workNo:'',
      field0057:'',
      projectNo:'',
      dictOptions:{
      },
      subExpandedKeys:[],
      columns:[
        {
          title: '项目名称',
          align:"center",
          dataIndex: 'field0047',
          key: 'field0047',
          width: 400,
          ellipsis: true
        }, {
          title: '工作令号',
          align: 'center',
          dataIndex: 'field0056',
          key: 'field0056',
          width: 200,
          ellipsis: true
        }, {
          title: '存货编码',
          align: 'center',
          dataIndex: 'field0057',
          key: 'field0057',
          ellipsis: true
        }, {
          title: '机械系统编码',
          align: 'center',
          dataIndex: 'field0054',
          key: 'field0054',
          ellipsis: true
        }, {
          title: '电气系统编码',
          align: 'center',
          dataIndex: 'field0055',
          key: 'field0055',
          ellipsis: true
        }, {
          title: '签约客户',
          align: 'center',
          dataIndex: 'field0048',
          key: 'field0048',
          ellipsis: true
        }, {
          title: '交期要求',
          align: 'center',
          dataIndex: 'field0050',
          key: 'field0050',
          scopedSlots: {
            customRender: 'tradeTime'
          }
        },
        // {
        //   title: '销售员',
        //   align: 'center',
        //   dataIndex: 'field0059',
        //   key: 'field0059'
        // },
        {
          title: '合同编号',
          align: 'center',
          dataIndex: 'field0068',
          key: 'field0068'
        }, {
          title: '项目编号',
          align: 'center',
          dataIndex: 'field0172',
          key: 'field0172'
        }
      ],
      planColumns: [
        {
          title: '物料编码',
          dataIndex: 'cno',
          width: 100,
          key: 'cno'
        },
        {
          title: '图号',
          dataIndex: 'f08',
          width: 130,
          key: 'f08'
        },
        {
          title: '名称',
          dataIndex: 'name',
          align: 'center',
          width: 100,
          key: 'name'
        }, {
          title: '单位',
          dataIndex: 'f02',
          key: 'f02',
          align: 'center',
          width: 80
        },
        {
          title: '制造方式',
          dataIndex: 'f04',
          width: 80,
          align: 'center',
          key: 'f04',
          scopedSlots: { customRender: 'updateF04' }
        },
        // ,{
        //   title: 'WIP属性',
        //   dataIndex: 'f05',
        //   key: 'f05',
        //   width: 80
        // },{
        //   title: '分类',
        //   dataIndex: 'f11',
        //   width: 80,
        //   key: 'f11'
        // },
        {
          title: '用量',
          dataIndex: 'bnum',
          key: 'bnum',
          align: 'center',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        },
        {
          title: '采购',
          dataIndex: 'cgqty',
          align: 'center',
          key: 'cgqty',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        },{
          title: '到货',
          dataIndex: 'dhqty',
          align: 'center',
          key: 'dhqty',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        },{
          title: '入库',
          dataIndex: 'rkqty',
          align: 'center',
          key: 'rkqty',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        },{
          title: '领料',
          dataIndex: 'llqty',
          align: 'center',
          key: 'llqty',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        }
        ,{
          title: '锁定',
          dataIndex: 'lockqty',
          align: 'center',
          key: 'lockqty',
          width: 70,
          scopedSlots: {
            customRender: 'tradeNum'
          }
        },
        {
          title: '库存',
          dataIndex: 'qty',
          align: 'center',
          key: 'qty',
          width: 70,
          scopedSlots: {
            customRender:'checkQty'
          },
        }
        // , {
        //   title: '物料状态',
        //   dataIndex: 'status',
        //   key: 'status',
        //   scopedSlots: { customRender: 'status' }
        // }
      ],
    }
  },
  created() {
    this.getOutSourceStatus()
  },
  computed:{
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
        }
      }
    },
  },
  methods: {
    searchQuery() {
      this.loadData(1);
      this.bomSource=[];
    },

    rowClassName(record, index) {
      return index === this.selectIndex ? 'Rowactive' : ''
    },

    clickThenSelect(record,index) {
      return {
        on: {
          click: () => {
            //当前行的索引
            let that = this
            that.selectIndex = index
            this.bomSource=[];
            this.workNo=record.field0056;
            this.projectNo=record.id;
            var field0057=record.field0057+','+record.field0054+','+record.field0055
            this.pno=field0057
            this.onSelectChangeByBoom(field0057,record.field0056);
          }
        }
      }
    },

    fatherMethodOther(str){
      this.onSelectChangeByBoom(this.pno,this.workNo);
    },



    onSelectChangeByBoom(field0057,workno) {
      this.loading = true
      let params = {
        'pno': field0057,
        'workno': workno
      }
      queryPBomByWms(params).then((res) => {
        if (res.code==0) {
          this.loading = false
          this.bomSource=this.getDataByResult(res.result.records);
        }else{
          this.loading = false
          this.bomSource=[];
          this.$message.error(res.message)
        }
      })
    },

    timeFormat(val) {
      return moment(val).format('YYYY-MM-DD')
    },
    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);
          }
        });
      }
    },
    numFormat(qty){
      if(qty==undefined){
        return '';
      }else{
        return  parseFloat(qty).toFixed(1);
      }
    },
    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);
        });
      }
    },

    confirmHandle(record) {
      var llqty=record.llqty;
      if (llqty==undefined){
        llqty='0';
      }
      var qty=record.qty;
      if (qty==undefined){
        qty='0';
      }
      var bnum=record.bnum;
      if (bnum==undefined){
        bnum='0';
      }
      var xnqty=parseInt(bnum)-parseInt(llqty)
      var status='';
      if (parseInt(llqty) >= parseInt(bnum)) {
        status= '2';
      } else {
        if (parseInt(xnqty) <= parseInt(qty)) {
          status= '1';
        } else {
          status= '0';
        }
      }
      if(record.qty==undefined){
        status='';
      }
      var actions = []
      Object.keys(this.outsourcingInStatusList).some((key) => {
        if (this.outsourcingInStatusList[key].value == ('' + status)) {
          actions.push(this.outsourcingInStatusList[key].text)
          return true
        }
      })
      return actions.join('')
    },

    solutionColor(record) {
      var llqty=record.llqty;
      if (llqty==undefined){
        llqty='0';
      }
      var qty=record.qty;
      if (qty==undefined){
        qty='0';
      }
      var bnum=record.bnum;
      if (bnum==undefined){
        bnum='0';
      }
      var xnqty=parseInt(bnum)-parseInt(llqty)
      var status='';
      if (parseInt(llqty) >= parseInt(bnum)) {
        status= '2';
      } else {
        if (parseInt(xnqty) <= parseInt(qty)) {
          status= '1';
        } else {
          status= '0';
        }
      }
      var actions = ''
      Object.keys(this.outsourcingInStatusList).some((key) => {
        if (this.outsourcingInStatusList[key].value == ('' + status)) {
          actions = this.outsourcingInStatusList[key].color
        }
      })
      return actions
    },

    getOutSourceStatus() {
      ajaxGetDictItems('bom_inv_status').then((res) => {
        if (res.success) {
          this.outsourcingInStatusList = res.result
        }
      })
    },


    getDataByResult(result){
      return result.map(item=>{
        //判断是否标记了带有子节点
        if(item[this.hasChildrenField]=='1'){
          let loadChild = { cno: item.cno+'_loadChild', name: 'loading...', isLoading: true }
          item.children = [loadChild]
        }
        return item
      })
    },

    handleExpand(expanded, record){
      // 判断是否是展开状态id
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length>0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams();//查询条件
          params[this.pidField] = record.cno
          params['uuid'] = record.uuid
          getAction(this.url.childList,params).then((res)=>{
            if(res.success){
              if(res.result && res.result.length>0){
                record.children = this.getDataByResult(res.result)
                this.bomSource = [...this.bomSource]
              }else{
                record.children=''
                record.hasChildrenField='0'
              }
            }else{
              this.$message.warning(res.message)
            }
          })

        }

      }else{
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if(keyIndex>=0){
          this.expandedRowKeys.splice(keyIndex, 1);
        }
      }
    },

    // 添加子分类时获取所有父级id
    getExpandKeysByPid(pid,arr,all){
      if(pid && arr && arr.length>0){
        for(let i=0;i<arr.length;i++){
          if(arr[i].cno==pid){
            this.subExpandedKeys.push(arr[i].cno)
            this.getExpandKeysByPid(arr[i]['pid'],all,all)
          }else{
            this.getExpandKeysByPid(pid,arr[i].children,all)
          }
        }
      }
    },
    getFormDataById(cno,arr){
      if(arr && arr.length>0){
        for(let i=0;i<arr.length;i++){
          if(arr[i].cno==cno){
            this.parentFormData = arr[i]
          }else{
            this.getFormDataById(cno,arr[i].children)
          }
        }
      }
    },
    expandTreeNode(nodeId){
      return new Promise((resolve,reject)=>{
        this.getFormDataById(nodeId,this.bomSource)
        let row = this.parentFormData
        this.expandedRowKeys.push(nodeId)
        let params = this.getQueryParams();//查询条件
        params[this.pidField] = nodeId
        getAction(this.url.childList,params).then((res)=>{
          console.log("11111",res)
          if(res.success){
            if(res.result && res.result.length>0){
              row.children = this.getDataByResult(res.result)
              this.bomSource = [...this.bomSource]
              resolve()
            }else{
              row.children=''
              row.hasChildrenField='0'
              reject()
            }
          }else{
            reject()
          }
        })
      })
    },

    // 根据已展开的行查询数据(用于保存后刷新时异步加载子级的数据)
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch,{ parentIds: this.expandedRowKeys.join(',') }).then(res=>{
          if (res.success && res.result.records.length>0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map();
            for (let item of records) {
              let pid = item[this.pidField];
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid);
                if (mapList == null) {
                  mapList = [];
                }
                mapList.push(item);
                listMap.set(pid, mapList);
              }
            }
            let childrenMap = listMap;
            let fn = (list) => {
              if(list) {
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.cno)) {
                    data.children = this.getDataByResult(childrenMap.get(data.cno))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },

    updateF04(record){
      this.$refs.pbomTypeForm.edit(record,this.workNo)
    },
    sendPbom(){
      this.$refs.pbomForm.edit(this.pno,this.workNo,this.bomSource.length,this.projectNo)
    },

    checkQty(record){
      this.$refs.materiaFrom.edit(record,this.workNo)
    },

    /** 点击a-table中的行后,展开或关闭其子行 */
    tableClick(record, index){
      return {
        style:{
          cursor:'pointer',
        },
        on: {
          click: () => {
            this.expandRowByClick = !this.expandRowByClick;
          }
        }
      }
    },
  }
}
</script>

<style scoped>

</style>