<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form
          :inline="true"
          class="demo-form-inline"
          label-position="right"
          label-width="80px"
          label-suffix=":"
        >
          <el-form-item label="工令号">
            <el-input
              v-model="query.workorder_code"
              size="mini"
              clearable
              placeholder="工令号"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="产品">
            <el-input
              v-model="query.material_id"
              size="mini"
              clearable
              placeholder="物料编码或物料编码"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="开单日期">
            <el-date-picker
              v-model="query.createTime"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              @change="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="配方状态">
            <el-select
              v-model="query.status"
              clearable
              size="mini"
              placeholder="配方状态"
              class="filter-item"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.formula_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-form-item label="批次">
              <el-input
                v-model="query.pcsn"
                size="mini"
                clearable
                placeholder="批次"
                @keyup.enter.native="crud.toQuery"
              />
            </el-form-item>
          </el-form-item>
          <rrOperation />
        </el-form>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          class="filter-item"
          type="success"
          :disabled="dissub_flag"
          icon="el-icon-position"
          size="mini"
          @click="cancel"
        >
          作废
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          :disabled="change_flag"
          icon="el-icon-check"
          size="mini"
          @click="typeChange"
        >
          配粉补料
        </el-button>
<!--        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          @click="pointCard"
        >
          打印工艺指令控制卡
        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          :disabled="Export_flag"
          @click="Export"
        >
          生成记录卡
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          :disabled="Export_flag"
          @click="save"
        >
          保存记录卡
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          :disabled="show_flag"
          @click="showCard"
        >
          查看记录卡
        </el-button>
      </crudOperation>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        size="mini"
        :data="crud.data"
        style="width: 100%;"
        :highlight-current-row="true"
        @selection-change="mySelectionChange"
      >
        <el-table-column  type="selection" width="55" />
        <el-table-column prop="formula_code" width="130" label="配方编号">
          <template slot-scope="scope">
            <el-link type="warning" @click="toView(scope.$index, scope.row)">{{ scope.row.formula_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="workorder_code" width="130" label="工令号" />
        <el-table-column prop="bucket_type" :formatter="bucket_typeFormat" min-width="80" label="桶类型" />
        <el-table-column prop="material_code" min-width="130" label="物料编码"/>
        <el-table-column :formatter="seriesFormat" min-width="130" prop="product_series_id" label="系列" />
        <el-table-column prop="pcsn" min-width="130" label="批次"/>
        <el-table-column prop="detail_count" min-width="100" label="明细数"/>
        <el-table-column prop="masterbucket_qty" min-width="100" label="重量" :formatter="crud.formatNum3"/>
        <el-table-column prop="status" :formatter="stateFormat" min-width="80" label="状态" />
        <el-table-column prop="create_time" min-width="150" label="开单时间"/>
        <el-table-column prop="create_name" min-width="150" label="开单人"/>
        <el-table-column prop="update_time" min-width="150" label="修改时间"/>
        <el-table-column prop="update_optname" min-width="150" label="修改人"/>
        <el-table-column prop="start_time" min-width="150" label="开始时间"/>
        <el-table-column prop="start_name" min-width="150" label="开始人"/>
        <el-table-column prop="end_time" min-width="150" label="结束时间"/>
        <el-table-column prop="end_name" min-width="150" label="结束人"/>
        <el-table-column prop="add_time" min-width="150" label="补料时间"/>
        <el-table-column prop="add_name" min-width="150" label="补料人"/>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <ViewDialog :dialog-show.sync="viewShow" :rowmst="mstrow" @AddChanged="querytable" />
    <DivDialog :dialog-show.sync="changeShow" :rowmst="mstrow" @DivChanged="querytable" />

    <!--    Excel模板上传弹出框-->
    <el-dialog
      title="提示"
      :visible.sync="dialogUpload"
      append-to-body
      width="30%"
      @close="handleClose"
    >
      <el-upload
        ref="upload"
        :limit="1"
        :headers="headers"
        class="upload-demo"
        :auto-upload="false"
        drag
        :action="baseApi +'/api/formula/pictures/'+formula_id"
        multiple
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        :on-error="handleError"
        :on-success="handleSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传不超过50MB的文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogUpload = false">取消</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </div>
    </el-dialog>
    <PicDialog ref="child" :dialog-show.sync="PicDialog" />
  </div>
</template>

<script>
import formula from '@/api/wms/pf/formula'
import CRUD, { crud, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DivDialog from '@/views/wms/pf/formula/DivDialog'
import ViewDialog from '@/views/wms/pf/formula/ViewDialog'
import crudseriesProcessRoute from "@/api/wms/pdm/seriesProcessRoute";
import {download} from "@/api/data";
import {downloadFile} from "@/utils";
import {getToken} from "@/utils/auth";
import {mapGetters} from "vuex";
import PicDialog from '@/views/wms/pf/formula/PicDialog'

export default {
  name: 'formula',
  components: { ViewDialog, DivDialog, crudOperation, rrOperation, udOperation, pagination, PicDialog },
  cruds() {
    return CRUD({ title: '工令', idField: 'formula_id', url: 'api/formula', crudMethod: { ...formula },
      optShow: {
        add: false,
        edit: false,
        del: false,
        reset: true,
        download: false
      }})
  },
  mixins: [presenter(), header(), crud()],
  // 数据字典
  dicts: ['formula_status', 'workorder_type', 'product_series', 'bucket_type'],
  data() {
    return {
      dialogUpload: false,
      PicDialog: false,
      formula_id: null,
      headers: { 'Authorization': getToken() },
      height: document.documentElement.clientHeight - 180 + 'px;',
      permission: {
      },
      divShow: false,
      dissub_flag: true,
      change_flag: true,
      Export_flag: true,
      show_flag: true,
      mstrow: {},
      viewShow: false,
      changeShow: false,
      currentRow: null,
      checkrows: [],
      XLList:[]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  created() {
    crudseriesProcessRoute.getXLlist2().then(res => {
      this.XLList = res
    })
  },
  methods: {
    canUd(row) {
      return row.status !== '10'
    },
    [CRUD.HOOK.beforeRefresh]() {
      this.handleCurrentChange()
    },
    toView(index, row) {
      this.mstrow = row
      this.viewShow = true
    },
    mySelectionChange(rows) {
      this.buttonChange(rows)
    },
    buttonChange(rows) {
      if (rows.length !== 0) {
        this.dissub_flag = false
        this.change_flag = false
        this.Export_flag = false
        this.show_flag = false
        for (let i = 0; i < rows.length; i++) {
          if (rows[i].status !== '20') {
            this.dissub_flag = true
          }
          if (rows[i].status === '99') {
            this.Export_flag = true
          }
          if (!'30,20'.includes(rows[i].status)  || rows.length !== 1) {//后台校验首道工序
            this.change_flag = true
          }
        }
      }else{
        this.handleCurrentChange()
      }
    },
    stateFormat(row) {
      return this.dict.label.formula_status[row.status]
    },
    bill_typeFormat(row) {
      return this.dict.label.workorder_type[row.workorder_type]
    },
    seriesFormat(row) {
      for (const item of this.XLList) {
        if (item.id === row.product_series_id) {
          return item.name
        }
      }
    },
    bucket_typeFormat(row) {
      return this.dict.label.bucket_type[row.bucket_type]
    },
    handleCurrentChange() {
      this.checkrows = []
      this.mstrow = {}
      this.dissub_flag = true
      this.change_flag = true
      this.Export_flag = true
      this.show_flag = true
    },
    checkboxT(row) {
      return row.status !== '99'
    },
    typeChange() {
      this.checkrows = this.$refs.table.selection
      if(this.checkrows.length !== 1 ){
        this.crud.notify('只能勾选一条记录开单！')
        return false
      }
      this.mstrow = this.checkrows.pop()
      this.changeShow = true
    },
    cancel(){
      this.checkrows = this.$refs.table.selection
      if(this.checkrows.length === 0){
        this.crud.notify('请先选择需要作废的配方记录！')
        return false
      }
      formula.cancel({'rows':this.checkrows}).then(res => {
        this.crud.notify('作废配方成功！')
        this.querytable()
      })
    },
    querytable() {
      this.crud.toQuery()
      this.handleCurrentChange()
    },
    pointCard() {
      const _selectData = this.$refs.table.selection
      if (_selectData.length === 0 || _selectData.length > 1) {
        this.crud.notify('请选择一条记录', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
      const data = _selectData[0]
      formula.pointCard(data).then(res => {
        this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.toQuery()
      })
    },
    Export() {
      const _selectData = this.$refs.table.selection
      if (_selectData.length === 0 || _selectData.length > 1) {
        this.crud.notify('请选择一条记录', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
      const data = _selectData[0]
      download('/api/formula/preview', { 'formula_id': data.formula_id }).then(result => {
        debugger
        const name = data.material_code + data.pcsn
        downloadFile(result, name, 'xlsx')
        crud.downloadLoading = false
      }).catch(() => {
        crud.downloadLoading = false
      })
    },
    save() {
      const _selectData = this.$refs.table.selection
      if (_selectData.length === 0 || _selectData.length > 1) {
        this.crud.notify('请选择一条记录', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
      const data = _selectData[0]
      this.formula_id = data.formula_id
      this.dialogUpload = true
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 50
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 50MB!')
      }
      return isLt2M
    },
    handleExceed(files, fileList) {
      this.crud.notify('当前限制最多能选择 1 个文件', CRUD.NOTIFICATION_TYPE.WARNING)
    },
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleSuccess(files, fileList) {
      this.file_name = files.name
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.dialogUpload = false
      this.crud.toQuery()
    },
    submitUpload() {
      const flag = this.$refs.upload.submit()
    },
    handleClose() {
      this.dialogUpload = false
    },
    showCard() {
      const _selectData = this.$refs.table.selection
      if (_selectData.length === 0 || _selectData.length > 1) {
        this.crud.notify('请选择一条记录', CRUD.NOTIFICATION_TYPE.INFO)
        return false
      }
      const data = _selectData[0]
      // 给子组件传值
      this.$refs.child.setForm(data.formula_id)
      this.PicDialog = true
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-dialog__body {
  padding-top: 10px;
}
</style>
