<template>
  <a-card :bordered="false">
<!--    &lt;!&ndash; 查询区域 &ndash;&gt;-->
<!--    <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="项目名称">-->
<!--              <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"-->
<!--                v-model="queryParam.bomId"-->
<!--                default-value="defaultValue"-->
<!--              >-->
<!--                <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>-->

<!--    &lt;!&ndash; table区域-begin &ndash;&gt;-->
<!--    <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"-->
<!--        :dataSource="treeDataSource"-->
<!--        :loading="planLoading"-->
<!--        :expandedRowKeys="expandedRowKeys"-->
<!--        @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="table-page-search-wrapper" style="margin-top: 20px">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-input v-model="queryParam.bomId" v-show="false"></a-input>
            <a-col :md="6" :sm="8">
              <a-form-item label="工作令号">
<!--                <a-input placeholder="请输入工作令号" v-model="queryParam.workNo"></a-input>-->
                <j-popup  v-model="queryParam.workNo" code="find_projectc" field="field0056" orgFields="field0056" destFields="field0056" :multi="true"/>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="采购单号">
                <a-input placeholder="请输入采购单号" v-model="queryParam.code"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="物料编码">
                <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="物料名称">
                <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
              </a-form-item>
            </a-col>

<!--            <a-col :md="6" :sm="8">-->
<!--              <a-form-item label="项目名称">-->
<!--                <a-input placeholder="请输入项目名称" v-model="queryParam.projectName"></a-input>-->
<!--              </a-form-item>-->
<!--            </a-col>-->

            <a-col :md="6" :sm="8">
              <a-form-item label="状态">
                <a-select
                  v-model="queryParam.status"    placeholder="请选择状态" >
                  <a-select-option v-for="item in statusList" :key="item.value" :value="item.value">{{ item.text }}</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="queryPurchaseIn" 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">
        <span style="float: left;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="print()" icon="printer">打印</a-button>
        </span>
        <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
             <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
                       :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" icon="import">导入</a-button>
              </a-upload>
          </span>
        <a-button type="primary" icon="download" @click="handleExportXls('采购表')">导出</a-button>
        <span>
            <a-button type="primary" @click="batchEditOpen()" icon="edit" style="margin-left: 8px">批量编辑</a-button>
        </span>
        <span>
            <a-button type="primary" @click="shipToSide()" icon="car" style="margin-left: 8px">直发现场</a-button>
        </span>
      </div>
      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="planColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: selectChanges}"
        @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-popconfirm title="回退会删除此采购计划,确定继续吗?" @confirm="() => returnPlan(record.id,record.status)">
            <a>回退计划</a>
          </a-popconfirm>
        </span>
      </a-table>

    <!-- 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>
    <ship-header-purchase-form ref="shipHeaderFrom"></ship-header-purchase-form>
  </a-card>


</template>

<script>
import { JeecgListMixin } from '../../mixins/JeecgListMixin'
import { deleteAction} from '@/api/manage'
import {
  getProjectName,
  getWorkNo,
  getProjectNo,
  getBomTree,
  getPurchase,
  getBomIdList,
  getBomId,
  ajaxGetDictItems
} from '../../api/api'
import PurchaseInModal from './modules/PurchaseInModal'
import PurchaseInBatchModal from './modules/PurchaseInBatchModal'
import PurchaseInPrintModal from './modules/PurchaseInPrintModal'
import moment from 'moment'
import MergeModal from './modules/mergeModal'
import ShipHeaderPurchaseForm from "./modules/ShipHeaderPurchaseForm";

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'
  }, {
    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'
  }
]
export default {
  name: 'PurchaseIn',
  mixins: [JeecgListMixin],
  components: {
    PurchaseInPrintModal,
    MergeModal,
    PurchaseInModal,
    PurchaseInBatchModal,
    ShipHeaderPurchaseForm
  },
  data() {
    return {
      disableMixinCreated: true,
      ids: '',
      printVisible: false,
      confirmLoading: false,
      planLoading: false,
      description: '这是采购入库页面',
      defaultValue: '',
      purchasedStatusList: [],
      treeDataSource: [],
      // 表头
      columns: columns,
      loading: false,
      // 展开的行,受控属性
      expandedRowKeys: [],
      printDataSource: [],
      printLoading: false,
      queryParam: [],
      projectNameList: [],
      workNoList: [],
      projectNoList: [],
      statusList:[],
      workNoArr:'',
      projectNameStr:'',
      materialCodeArr:'',
      materialNameArr:'',
      unitArr:'',
      qtyArr:'',
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['10', '50', '100', '200', '300'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      bomIdList: [],
      batchForm: this.$form.createForm(this),
      planColumns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          key: 'projectName'
        },
        {
          title: '工作令',
          dataIndex: 'workNo',
          key: 'workNo'
        },
        {
          title: '采购单号',
          dataIndex: 'code',
          key: 'code'
        }, {
          title: '编码',
          dataIndex: 'materialCode',
          key: 'materialCode'
        }, {
          title: '名称',
          dataIndex: 'materialName',
          key: 'materialName'
        }, {
          title: '单位',
          dataIndex: 'unit',
          key: 'unit'
        }, {
          title: '数量',
          dataIndex: 'qty',
          key: 'qty'
        },{
          title: '到货',
          dataIndex: 'inQty',
          key: 'inQty'
        }, {
          title: '发货',
          dataIndex: 'outQty',
          key: 'outQty'
        }, {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        // {
        //   title: '供应商',
        //   dataIndex: 'supplier',
        //   key: 'supplier'
        // }, {
        //   title: '联系人',
        //   dataIndex: 'contact',
        //   key: 'contact'
        // },
        // {
        //   title: '联系方式',
        //   dataIndex: 'phone',
        //   key: 'phone'
        //   // },{
        //   //   title: '计划开始时间',
        //   //   dataIndex: 'planStartTime',
        //   //   key: 'planStartTime'
        // },
        {
          title: '初次',
          dataIndex: 'planEndTime',
          key: 'planEndTime',
          align: 'center',
          scopedSlots: {
            customRender: 'tradeTime'
          }
         },{
          title: '变更',
          dataIndex: 'changePlanEndTime',
          key: 'changePlanEndTime',
          scopedSlots: {
            customRender: 'tradeTime'
          }
        },{
          title: '到货时间',
          dataIndex: 'actualEndTime',
          key: 'actualEndTime',
          align: 'center',
          scopedSlots: {
            customRender: 'tradeTime'
          }
        },{
          title: '收货时间',
          dataIndex: 'receiptTime',
          key: 'receiptTime',
          align: 'center',
          scopedSlots: {
            customRender: 'tradeTime'
          }
        },{
          title: '领料时间',
          dataIndex: 'pickingTime',
          key: 'pickingTime',
          align: 'center',
          scopedSlots: {
            customRender: 'tradeTime'
          }
        }, {
          title: '长周期',
          dataIndex: 'flag',
          key: 'flag',
          align: 'center',
          scopedSlots: { customRender: 'flag' },
        }, {
          title: '备注',
          dataIndex: 'remark',
          key: 'remark'
        }, {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 150
        }
      ],
      url: {
        list: '/material/purchase/list',
        importExcelUrl: '/material/purchase/importExcel',
        exportXlsUrl: '/material/purchase/exportXls',
        delete: "/material/purchase/delete",
      }
    }
  },
  created() {
    this.loadFrom()
    this.getPurchaseStatus()
  },
  methods: {
    returnPlan(id,status){
      var that = this;
      if (status!="0"){
        that.$message.warning("只有采购中状态才能回退!");
        return false;
      }

      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    selectChanges(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      var array='';
      var array1='';
      var array2='';
      var array3='';
      var array4='';
      var firstWorkNo='';
      var firstName='';
      var i=0;
      this.selectionRows.forEach(function (row) {
        i++;
        if (i=1){
          firstWorkNo=row.workNo;
          firstName=row.projectName;
        }
        if (firstWorkNo!=row.workNo){
          this.$message.warning("请选择一个工作令里的物料");
          return false;
        }
        array1 += row.materialCode + ",";
        array2 += row.materialName + ",";
        array3 += row.unit + ",";
        array4 += row.qty + ",";
      });
      this.workNoArr=firstWorkNo;
      this.projectNameStr=firstName;
      this.materialCodeArr=array1;
      this.materialNameArr=array2;
      this.unitArr=array3;
      this.qtyArr=array4;
    },
    shipToSide(){
      this.$refs.shipHeaderFrom.edit(this.projectNameStr,this.workNoArr,this.materialCodeArr,this.materialNameArr,this.unitArr,this.qtyArr,'采购');
    },
    loadFrom() {
      ajaxGetDictItems('purchased_status').then((res)=> {
        if (res.success) {
          this.statusList = res.result
        }
      })
      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
      )
    },
    loadTreeData(tree) {
      this.planLoading = false
      this.treeDataSource = tree
    },

    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
    },
    handleBomChange(value) {
      this.initBomTree(value)
    },
    query() {
      this.planLoading = 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.planLoading = false
        }
      })
    },
    queryPurchaseIn() {
      this.loading = true
      let params = {
        'workNo': this.queryParam.workNo,
        'materialCode': this.queryParam.materialCode,
        'materialName': this.queryParam.materialName,
        'status': this.queryParam.status,
        'code': this.queryParam.code,
        'projectName': this.queryParam.projectName,
      }
      this.getPurchaseList(params)
    },
    batchEditOpen() {
      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] + ','
        }
        this.$refs.batchModalForm.edit(this.ids)
      }
    },
    initBomTree(bomId) {
      let params = {
        'bomId': bomId
      }
      this.queryParam.bomId = bomId
      getBomTree(params).then((res) => {
        if (res.success) {
          this.loadTreeData(res.result)
        } else {
          this.$message.warning(res.message)
        }
      })
      this.getPurchaseList(params)
    },
    getPurchaseList(params) {
      getPurchase(params).then((res) => {
        if (res.success) {
          this.loading = false
          this.dataSource = res.result.records
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        }
      })
    },
    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>