<template>

  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form  layout="inline" @keyup.enter.native="query">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="项目名称">
              <a-select
              show-search
              placeholder="请输入项目名称"
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="queryParam.projectName"
              >
              <a-select-option v-for="item in projectNameList" :key="item" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="项目编码">
              <a-select
                show-search
                placeholder="请输入项目编码"
                option-filter-prop="children"
                :filter-option="filterOption"
                v-model="queryParam.projectNo"
              >
                <a-select-option v-for="item in projectNoList" :key="item" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="工作令号">
              <a-select
                show-search
                placeholder="请输入工作令号"
                option-filter-prop="children"
                :filter-option="filterOption"
                v-model="queryParam.workNo"
              >
                <a-select-option v-for="item in workNoList" :key="item" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="bomId">
              <a-select
                show-search
                placeholder="请选择BOM"
                option-filter-prop="children"
                :filter-option="filterOption"
                @change="handleBomChange"
                default-value="defaultValue"
                v-model="queryParam.bomId"
              >
                <a-select-option v-for="item in bomIdList" :key="item" :value="item">{{ item }}</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="query" 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>


    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="handleConfirm" type="primary" icon="check">确认</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
    </div>

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

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        :columns="columns"
        :scroll="{x: 1500}"
        size="middle"
        :pagination="false"
        :dataSource="dataSource"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, onSelectAll: onSelectAll, onSelect: onSelect}"
        @expandedRowsChange="handleExpandedRowsChange">

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

        <span slot="confirm" slot-scope="confirm">
          <a-tag :key="confirm" :color="confirm?'#2db7f5':'#87d068'">
            {{ confirmHandle(confirm) }}
          </a-tag>
        </span>

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

    </div>
    <!-- table区域-end -->

    <bom-modal ref="modalForm" @ok="modalFormOk"></bom-modal>
  </a-card>

</template>

<script>
import {JeecgListMixin} from '../../mixins/JeecgListMixin'
import {
  getBomId,
  getBomTree,
  getProjectName,
  getWorkNo,
  getProjectNo,
  getBomIdList,
  confirmMaterial,
  ajaxGetDictItems
} from '../../api/api'
import BomModal from './modules/BomModal'

const columns = [
  {
    title: '图号',
    dataIndex: 'drawingNo',
    key: 'drawingNo'
  },
  {
  //   title: 'BOM',
  //   dataIndex: 'bomId',
  //   key: 'bomId'
  // }, {
    title: '物料编码',
    dataIndex: 'code',
    key: 'code'
  }, {
    title: '物料名称',
    dataIndex: 'name',
    key: 'name'
  },{
    title: '物料单位',
    dataIndex: 'unit',
    key: 'unit'
  }, {
    title: '用量',
    dataIndex: 'number',
    key: 'number'
  },{
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' }
  },{
    title: '制造方式',
    dataIndex: 'method',
    key: 'method'
  },{
    title: '设计类型',
    dataIndex: 'designType',
    key: 'designType'
  },{
    title: 'WIP属性',
    dataIndex: 'wipType',
    key: 'wipType'
  },{
    title: '品牌',
    dataIndex: 'brand',
    key: 'brand'
  }, {
    title: '分类',
    dataIndex: 'categories',
    key: 'categories'
  }, {
    title: '是否确认',
    dataIndex: 'confirm',
    key: 'confirm',
    scopedSlots: { customRender: 'confirm' }
  },{
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150
  }
]
export default {
  name: 'BomList',
  mixins: [JeecgListMixin],
  components: {
    BomModal
  },
  data() {
    return {
      description: '这是菜单管理页面',
      // 表头
      columns: columns,
      loading: false,
      // 展开的行,受控属性
      expandedRowKeys: [],
      defaultValue: 0,
      url: {
        list: '/config/bom/list',
        delete: '/config/bom/delete',
        deleteBatch: '/config/bom/deleteBatch',
        importExcelUrl: '/config/bom/importExcel'
      },
      queryParam: {},
      projectNameList: [],
      workNoList: [],
      projectNoList: [],
      bomIdList: [],
      purchasedStatusList: [],
      outsourcingInStatusList: [],
      selfMadeStatusList: []
    }
  },
  created() {
    this.loadFrom()
    this.getPurchaseStatus()
    this.getOutsourcingInStatus()
    this.getSelfMadeStatusList()
  },
  methods: {
    loadFrom() {
      getProjectName().then((res) => {
        if (res.success) {
          this.projectNameList = res.result
        }
      })
      getWorkNo().then((res) => {
        if (res.success) {
          this.workNoList = res.result
        }
      })
      getProjectNo().then((res) => {
        if (res.success) {
          this.projectNoList = res.result
        }
      })
      // getBomIdList().then((res) => {
      //   if (res.success) {
      //     this.bomIdList = res.result
      //   }
      // })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    loadData(tree) {
      this.dataSource = tree;
    },

    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
    },

    query()  {
      let params = {
        "bomId": this.queryParam.bomId,
        "projectName": this.queryParam.projectName,
        "projectNo": this.queryParam.projectNo,
        "workNo": this.queryParam.workNo
      }
      this.loading = true
      getBomId(params).then((res) => {
        if (res.success) {
          this.bomIdList = [];
          for (let i=0;i<res.result.length;i++) {
            this.bomIdList.push(res.result[i])
          }
          // this.defaultValue = this.bomIdList[0]
          this.initBomTree(this.bomIdList[0])
          this.queryParam.bomId = this.bomIdList[0]
        } else {
          this.$message.error(res.message)
        }
      })
    },

    /**
     * @function 任务类型文本框的值变化时的回调
     * @author ***
     * @time 2020-08-17
     **/
    handleSearch (value) {
      this.handleChange(value);
    },

    handleBomChange(value) {
      this.initBomTree(value);
    },
    initBomTree(bomId) {
      this.loading = true
      let params = {
        "bomId": bomId
      }
      getBomTree(params).then((res) => {
        if (res.success) {
          this.loading = false
          this.loadData(res.result)
        }
      })
    },
    onSelectAll(selected) {
      if (selected) {
        const tabData = this.dataSource;
        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.dataSource;
      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;
          }
        }
      }
    },
    handleConfirm() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录!')
      } else {
        this.ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          this.ids += this.selectedRowKeys[a] + ','
        }
        let params = {
          "ids": this.ids,
          "bomId": this.queryParam.bomId
        }
        confirmMaterial(params).then((res)=> {
          if (res.success) {
            this.initBomTree(this.queryParam.bomId)
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    solutionStatus(record) {
      let actions = []
      if (record.method == "外购") {
        Object.keys(this.purchasedStatusList).some((key) => {
          if (this.purchasedStatusList[key].value == ('' + record.status)) {
            actions.push(this.purchasedStatusList[key].text)
            return true
          }
        })
        return actions.join('')
      } else if (record.method == "外协") {
        Object.keys(this.outsourcingInStatusList).some((key) => {
          if (this.outsourcingInStatusList[key].value == ('' + record.status)) {
            actions.push(this.outsourcingInStatusList[key].text)
            return true
          }
        })
        return actions.join('')
      } else if (record.method == "自制") {
        Object.keys(this.selfMadeStatusList).some((key) => {
          if (this.selfMadeStatusList[key].value == ('' + record.status)) {
            actions.push(this.selfMadeStatusList[key].text)
            return true
          }
        })
        return actions.join('')
      } else {
        actions.push("未知")
        return actions.join('')
      }
    },
    solutionStatusColor(record) {
      let actions = ''
      if (record.method == "外购") {
        Object.keys(this.purchasedStatusList).some((key) => {
          if (this.purchasedStatusList[key].value == ('' + record.status)) {
            actions = this.purchasedStatusList[key].color
          }
        })
        return actions
      } else if (record.method == "外协") {
        Object.keys(this.outsourcingInStatusList).some((key) => {
          if (this.outsourcingInStatusList[key].value == ('' + record.status)) {
            actions = this.outsourcingInStatusList[key].color
          }
        })
        return actions
      } else if (record.method == "自制") {
        Object.keys(this.selfMadeStatusList).some((key) => {
          if (this.selfMadeStatusList[key].value == ('' + record.status)) {
            actions = this.selfMadeStatusList[key].color
          }
        })
        return actions
      } else {
        actions = "#f50"
        return actions
      }

    },
    getPurchaseStatus() {
      ajaxGetDictItems('purchased_status').then((res) => {
        if (res.success) {
          this.purchasedStatusList = res.result
        }
      })
    },
    getOutsourcingInStatus() {
      ajaxGetDictItems('outsourcing_status').then((res) => {
        if (res.success) {
          this.outsourcingInStatusList = res.result
        }
      })
    },
    getSelfMadeStatusList() {
      ajaxGetDictItems('self_made_status').then((res) => {
        if (res.success) {
          this.selfMadeStatusList = res.result
        }
      })
    },
    confirmHandle(confirm) {
      return confirm ? '是' : '否'
    }
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  }
}
</script>

<style scoped>

</style>