<!-- 任务处理中心 -->
<template>
  <div class="production">
    <template v-if="!detailsVisible && !outsourceVisible && !checkVisible && !preCheckVisible && !purchaseVisible && !printLabelVisible && !addOrUpdateVisible && !addOrUpdateOutsourceVisible">
      <el-header style="font-size: large;text-align: center">任务处理中心</el-header>
      <el-form>
        <el-form-item>
          <el-button v-if="isAuth('prod:production:purchase')" type="primary" @click="batchBuyHandle()" :disabled="batchIncomeBtnDisabled">批量转采购</el-button>
          <el-button v-if="isAuth('pur:commDetail:save')" type="primary" @click="batchOutsourceHandle()" :disabled="batchBtnDisabled">批量转委外</el-button>
        </el-form-item>
      </el-form>
      <el-table
        @selection-change="handleSelectionChange"
        :data="dataList"
        row-key="id"
        border
        :indent='20'
        lazy
        :load="loadingData"
        v-loading="dataListLoading"
        style="width: 100%;">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center">
        </el-table-column>
        <el-table-column
          prop="orderCode"
          header-align="center"
          align="center"
          min-width="200"
          :show-tooltip-when-overflow="true"
          label="任务单编码">
        </el-table-column>
        <el-table-column
          prop="mapNumber"
          header-align="center"
          align="center"
          min-width="120"
          :show-tooltip-when-overflow="true"
          label="图号">
        </el-table-column>
        <el-table-column
          prop="productName"
          header-align="center"
          align="center"
          min-width="160"
          :show-tooltip-when-overflow="true"
          label="物料名称">
        </el-table-column>
        <el-table-column
          prop="productSpec"
          header-align="center"
          align="center"
          min-width="160"
          :show-tooltip-when-overflow="true"
          label="规格">
        </el-table-column>
        <el-table-column
          prop="materials"
          header-align="center"
          align="center"
          min-width="160"
          :show-tooltip-when-overflow="true"
          label="材料">
        </el-table-column>
        <el-table-column
          prop="productNumber"
          header-align="center"
          align="center"
          min-width="120"
          :show-tooltip-when-overflow="true"
          label="生产编号">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="对应工艺">
          <template slot-scope="scope">
            <el-button :disabled="!scope.row.techId" type="text" size="small" @click="techDetails(scope.row.techId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="cnt"
          header-align="center"
          align="center"
          min-width="100"
          label="数量">
        </el-table-column>
        <el-table-column
          prop="isAppraise"
          header-align="center"
          align="center"
          :formatter="formatAppraise"
          label="是否鉴定">
        </el-table-column>
        <el-table-column
          prop="isFirst"
          header-align="center"
          align="center"
          :formatter="formatFirst"
          label="是否首件">
        </el-table-column>
        <el-table-column
          prop="deliveryDate"
          header-align="center"
          align="center"
          min-width="160"
          label="交期时间">
        </el-table-column>
        <el-table-column
          prop="batchNumber"
          header-align="center"
          align="center"
          min-width="140"
          :show-tooltip-when-overflow="true"
          label="批次号">
        </el-table-column>
        <el-table-column
          prop="notes"
          header-align="center"
          align="center"
          width="180"
          :show-tooltip-when-overflow="true"
          label="备注">
        </el-table-column>
        <el-table-column
          prop="inventoryCnt"
          header-align="center"
          align="center"
          min-width="140"
          label="仓库核对数量">
        </el-table-column>
        <el-table-column
          prop="customerName"
          header-align="center"
          align="center"
          min-width="160"
          :show-tooltip-when-overflow="true"
          label="客户名称">
        </el-table-column>
        <el-table-column
          prop="contractNumber"
          header-align="center"
          align="center"
          min-width="140"
          :show-tooltip-when-overflow="true"
          label="合同编号">
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="prodState"
          header-align="center"
          align="center"
          width="120"
          :formatter="formatState"
          label="当前状态">
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="state"
          header-align="center"
          align="center"
          :formatter="formatState2"
          label="处理状态">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="240"
          label="操作">
          <template slot-scope="scope">
            <el-button v-if="isAuth('prod:production:updateCheck') && Number(scope.row.prodState) === 0" type="text" size="small" @click="check(scope.row)">核料</el-button>
            <el-button v-if="isAuth('prod:production:purchase') && Number(scope.row.prodState) === 2" type="text" size="small" @click="purchaseHandle(scope.row)">转采购</el-button>
            <el-button v-if="isAuth('pur:commDetail:save') && Number(scope.row.prodState) === 2" type="text" size="small" @click="outsourceHandle(scope.row)">转委外</el-button>
<!--            <el-button v-if="isAuth('prod:production:examine') && Number(scope.row.prodState) === 1" type="text" size="small" @click="preCheck(scope.row.id)">试制前检查</el-button>-->
            <el-button v-if="isAuth('prod:production:plan') && Number(scope.row.prodState) === 2" type="text" size="small" @click="detail(scope.row.id, true)" v-reClick>排产</el-button>
<!--            <el-button v-if="isAuth('pur:commDetail:save') && Number(scope.row.outsourcing) === 0" type="text" size="small" @click="outsourceHandle(scope.row.id)">委外生产</el-button>-->
            <el-button type="text" size="small" @click="printLabel(scope.row)">打印标签 + {{scope.row.printCnt}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </template>
    <!-- 弹窗, 新增 / 修改 -->
    <detail v-if="detailsVisible" ref="details" @close="closeDialogEvent" @refreshDataList="getDataList" @onChose="onChose"/>
    <!-- 委外 -->
    <scheduling-commission v-if="outsourceVisible" ref="outsource" @refreshDataList="getDataList" @onChose="onChose"/>
    <!-- 采购 -->
    <scheduling-purchase v-if="purchaseVisible" ref="purchase" @refreshDataList="getDataList" @onChose="onChose"/>
    <!-- 核料 -->
    <scheduling-check v-if="checkVisible" ref="check" @refreshDataList="getDataList" @onChose="onChose"/>
    <!-- 试制前检查 -->
    <scheduling-pre-check v-if="preCheckVisible" ref="preCheck" @refreshDataList="getDataList" @onChose="onChose"/>
    <!-- 对应工艺 -->
    <crafts-detail v-if="craftsVisible" ref="craftsDetail"/>
    <!-- 打印标签 -->
    <print-label v-if="printLabelVisible" ref="printLabel" @onChose="onChose" @addOne="addOneClick"/>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" :options-type="optionsType" @refreshDataList="getDataList" @onChose="onChose"></add-or-update>
    <!-- 委外 -->
    <outsource-add-or-update v-if="addOrUpdateOutsourceVisible" ref="addOrUpdateOutsource" @refreshDataList="getDataList" @onChose="onChose"></outsource-add-or-update>
  </div>
</template>

<script>
  import Detail from './scheduling-details'
  import OutsourceAddOrUpdate from '@/views/modules/sale/outsource-add-or-update'
  import { getSchedulingList, getChildren } from '@/api/production'
  import SchedulingCheck from '@/views/modules/production/scheduling-check'
  import SchedulingPreCheck from '@/views/modules/production/scheduling-pre-check'
  import PurchaseAddOrUpdate from '@/views/modules/sale/purchase-add-or-update'
  import SchedulingPurchase from '@/views/modules/production/scheduling-purchase'
  import SchedulingCommission from '@/views/modules/production/scheduling-commission'
  import CraftsDetail from '@/views/modules/tech/crafts-detail-dialog'
  import {downloadUrl} from '@/api/file'
  import PrintLabel from '@/views/modules/production/components/print-label.vue'
  import AddOrUpdate from '@/views/modules/sale/purchase-add-or-update'
  import { getDictList } from '@/api/dict'
export default {
    name: 'scheduling',
    components: {
      PrintLabel,
      CraftsDetail,
      SchedulingCommission,
      SchedulingPurchase,
      PurchaseAddOrUpdate,
      SchedulingPreCheck,
      SchedulingCheck,
      Detail,
      AddOrUpdate,
      OutsourceAddOrUpdate
    },
    data () {
      return {
        detailsVisible: false,
        outsourceVisible: false,
        checkVisible: false,
        preCheckVisible: false,
        purchaseVisible: false,
        craftsVisible: false,
        printLabelVisible: false,
        addOrUpdateVisible: false,
        addOrUpdateOutsourceVisible: false,
        dataForm: {},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        // 当前状态
        optionsProdState: [
          {
            code: '0',
            value: '待核料'
          },
          {
            code: '1',
            value: '待试制前检查'
          },
          {
            code: '2',
            value: '待排产'
          },
          {
            code: '3',
            value: '生产中'
          },
          {
            code: '4',
            value: '生产完成'
          },
          {
            code: '5',
            value: '不合格完成'
          }
        ],
        // 处理状态
        optionsState: [
          {
            code: '2',
            value: '待处理'
          },
          {
            code: '3',
            value: '采购'
          },
          {
            code: '4',
            value: '委外'
          },
          {
            code: '5',
            value: '生产'
          }
        ],
        multipleSelection: [],
        selectedRows:[],
        batchIncomeBtnDisabled: false,
        batchBtnDisabled: false,
        optionsType: [],
      }
    },
    created () {
      this.getTypeList()
      this.getDataList()
    },
    methods: {
      onChose () {
        this.detailsVisible = false
        this.outsourceVisible = false
        this.checkVisible = false
        this.preCheckVisible = false
        this.purchaseVisible = false
        this.craftsVisible = false
        this.printLabelVisible = false
        this.selectedRows = []
        this.batchIncomeBtnDisabled = false
        this.batchBtnDisabled = false
        this.addOrUpdateVisible = false
        this.addOrUpdateOutsourceVisible = false
      },
       // 获取采购类别字典
      getTypeList () {
        getDictList({type: 'purchase_type'}).then(({data}) => {
          if (data) {
            this.optionsType = data
          }
        })
      },
      // 查询
      queryPage () {
        this.pageIndex = 1
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.selectedRows = []
        this.batchIncomeBtnDisabled = false
        this.batchBtnDisabled = false

        this.dataListLoading = true
        let params = {
          'current': this.pageIndex,
          'size': this.pageSize
        }
        getSchedulingList(params).then(({data}) => {
          if (data && data.code === '200') {
            this.dataList = data.data.records
            // 设置已打印标签数量的初始值
            if (this.dataList) {
              this.dataList.forEach((item) => {
                item.printCnt = 0
              })
            }
            this.totalPage = Number(data.data.total)
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      detail (id, disable) {
        this.detailsVisible = true
        this.$nextTick(() => {
          this.$refs.details.init(id, disable)
        })
      },
      // 转换属性：是否
      formatAppraise (row) {
        if (!row.isAppraise) return ''
        return row.isAppraise === '1' ? '否' : '是'
      },
      // 转换属性：是否
      formatFirst (row) {
        if (!row.isFirst) return ''
        return row.isFirst === '1' ? '否' : '是'
      },
      // 转换属性“当前状态”
      formatState (row) {
        if (!row.prodState) return ''
        const item1 = this.optionsProdState.find((item) => item.code === row.prodState.toString())
        return item1 ? item1.value : ''
      },
      // 转换属性“处理状态”
      formatState2 (row) {
        if (!row.state) {
          return ''
        }
        const item1 = this.optionsState.find((item) => item.code === row.state.toString())
        return item1 ? item1.value : ''
      },
      closeDialogEvent () {
        this.detailsVisible = false
      },
      // 委外生产
      outsourceHandle (row) {
        this.outsourceVisible = true
        this.$nextTick(() => {
          this.$refs.outsource.init(row)
        })
      },
      // 采购
      purchaseHandle (row) {
        this.purchaseVisible = true
        this.$nextTick(() => {
          this.$refs.purchase.init(row)
        })
      },
      // 核料
      check (row) {
        this.checkVisible = true
        this.$nextTick(() => {
          this.$refs.check.init(row)
        })
      },
      // 核料
      preCheck (id) {
        this.preCheckVisible = true
        this.$nextTick(() => {
          this.$refs.preCheck.init(id)
        })
      },
      // 标签打印
      printLabel (row) {
        this.printLabelVisible = true
        this.$nextTick(() => {
          this.$refs.printLabel.init(row)
        })
      },
      // 对应工艺
      techDetails (id) {
        this.craftsVisible = true
        this.$nextTick(() => {
          this.$refs.craftsDetail.init(id)
        })
      },
      loadingData (row, treeNode, resolve) {
        getChildren(row.id).then(({data}) => {
          if (data && data.code === '200') {
            data.data.forEach(item => {
              if (item.attachList2 && item.attachList2.length > 0) {
                item.simplePic = downloadUrl + item.attachList2[0].url
              } else {
                item.simplePic = ''
              }
            })
            resolve(data.data)
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      addOneClick (row) {
        // this.dataList 中匹配 row.id，找到对应的数据
        this.dataList.forEach((item) => {
          if (item.id === row.id) {
            if (!item.printCnt) {
              item.printCnt = 0
            }
            item.printCnt += 1
          }
        })
      },
      //监听批量选择的行
      handleSelectionChange(rows){
        this.selectedRows = rows

        //控制批量操作按钮
        this.batchIncomeBtnDisabled = false
        this.batchBtnDisabled = false
        for(let index=0;index<this.selectedRows.length;index++){
          let item = this.selectedRows[index]
          if(Number(item.prodState) === 2){
          
          } else {
            this.batchIncomeBtnDisabled = true
          }

          if(Number(item.prodState) === 2){
          
          } else {
            this.batchBtnDisabled = true
          }
        }
      },
      //批量转采购
      batchBuyHandle(){
        if(this.selectedRows.length == 0){
           this.$message.error("请先勾选数据")
           return
        }

        let list = []
        this.selectedRows.forEach(item => {
          list.push({
            detailId:Math.round(Math.random() * 1000000),
            materialName: item.materialName,
            specification:item.productSpec,
            purchaseType: '',
            cnt:item.cnt,
            unitName:'',
            deadline:'',
            batchNumber:item.batchNumber,
            notes:''
          })
        })

        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(0, null, null, list)
        })
      },
      //批量转委外
      batchOutsourceHandle(){
        if(this.selectedRows.length == 0){
           this.$message.error("请先勾选数据")
           return
        }

        let list = []
        this.selectedRows.forEach(item => {
          list.push({
            detailId:Math.round(Math.random() * 1000000),
            productName: item.productName,
            productNumber:item.productNumber,
            productSpec: item.productSpec,
            cnt:item.cnt,
            unitName:'',
            deadline:'',
            batchNumber:item.batchNumber,
            arrivedTime:'',
            qualifiedCnt:'',
            price:'',
            taxPrice:'',
            taxAmount:'',
            taxRateVal:'',
            specificationExplian:'',
            notes:''
          })
        })

        this.addOrUpdateOutsourceVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdateOutsource.init(null,null,null,list)
        })
      }
    }
  }
</script>

<style scoped>

</style>
