<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container" v-loading="this.loading_add" element-loading-text="拼命加载中" element-loading-background="rgba(0, 0, 0, 0.1)">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.stationType" clearable filterable placeholder="工位" style="width: 150px;" class="filter-item"
                   @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="baseStatus in dict.station_type"
            :key="baseStatus.id"
            :label="baseStatus.label"
            :value="baseStatus.value"
          />
        </el-select>
        <el-input v-model="query.bigItemIdModes" clearable placeholder="型式品番" style="width: 150px;"
                  class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.bigItemIdModesName" clearable placeholder="型式名" style="width: 150px;"
                  class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.startNumber" clearable placeholder="起始机号" style="width: 150px;"
                  class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        /> <el-input v-model="query.endNumber" clearable placeholder="结束机号" style="width: 150px;"
                     class="filter-item"
                     @keyup.enter.native="crud.toQuery"
      />
        <el-select v-model="query.status" clearable placeholder="耗用状态" style="width: 120px;" class="filter-item"
                   @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="baseStatus in dict.hy_status"
            :key="baseStatus.id"
            :label="baseStatus.label"
            :value="baseStatus.value"
          />
        </el-select>

        <rrOperation :crud="crud"/>

      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-button
          slot="right"
          v-permission="permission.ops"
          class="filter-item"
          type="primary"
          size="mini"
          v-if="false"
          @click="collectFromFlag = true"
        >
          批量新增
        </el-button>
        <el-button size="mini" type="success" slot="right" class="filter-item"  v-permission="permission.hySpareParts"
                   @click="hySparePartsBtn(crud.selections)" :disabled="hySparePartsDisabled"
        >耗  用
        </el-button>
      </crudOperation>
      <!--新增的表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="500px" @close="fromeClose()"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="工位" prop="stationType" >
            <el-select v-model="form.stationType" @change="getBigItem(form.stationType)" value-key="id" filterable
                       placeholder="请选择" style="width: 370px;"
            >
              <el-option
                v-for="item in dict.station_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="型号品番" prop="bigItemId">
            <el-select v-model="form.bigItemId" value-key="id" @change="getBigItemName(form.bigItemId.name)" filterable
                       placeholder="请选择" style="width: 370px;"
            >
              <el-option
                v-for="item in bigItems"
                :key="item.id"
                :label="item.code"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="型式名">
            <el-input v-model="this.bigItemName" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="数量" prop="orderQuantity">
            <el-input v-model="form.orderQuantity" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="下线日期">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期时间"
              default-time="12:00:00"
              style="width: 370px;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="起始机号" prop="startNumber">
            <el-input v-model="form.startNumber" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="结束机号" prop="endNumber">
            <el-input v-model="form.endNumber" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 4}"
              placeholder="请输入内容"
              v-model="form.description" style="width: 370px;"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <!--批量新增-->
      <el-dialog title="批量新增" :visible.sync="collectFromFlag" width="400px">
        <el-form ref="collectFrom" :model="collectFrom" :rules="rules" size="small" label-width="80px">
          <el-form-item label="截止IDNO" prop="idno" >
            <el-input v-model="collectFrom.idno" :rows="3" type="textarea" style="width: 270px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="collectFromFlag= false">取 消</el-button>
          <el-button type="primary" @click="collectFromBtn">确 定</el-button>
        </div>
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler" :height="crud.tableHeight" border @select="selectData" @select-all="selectAllData"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="station_type#stationType" label="工位" width="120">
          <template slot-scope="scope">
            {{ dict.label.station_type[scope.row.stationType] }}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="下线日期">
          <template slot-scope="scope">
            {{ getFormatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="bigItemId.code" label="型式品番" width="120"/>
        <el-table-column prop="bigItemId.name" label="型式名" width="120"/>
        <el-table-column prop="orderQuantity" label="数量" width="70"/>
        <el-table-column prop="hy_status#status" label="状态"  width="70">
          <template slot-scope="scope">
            {{ dict.label.hy_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="startNumber" label="起始机号" width="80"/>
        <el-table-column prop="endNumber" label="结束机号"  width="80"/>
        <el-table-column prop="description" label="备注"/>
        <el-table-column prop="updateTime" label="操作日期" width="140"/>
        <el-table-column prop="updateBy" label="操作人" width="70"/>
        <el-table-column v-if="checkPer(['admin','spareparts:edit','spareparts:del'])" label="操作" width="200px"
                         align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              v-if="checkPer(['admin','spareparts:edit'])"
              @click="doXiuGai(scope.row)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              v-if="checkPer(['admin','spareparts:del'])"
              @click="doShanChu(scope.row)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import crudSpareparts, {hySpareParts,autoAddHy} from '@/api/spareparts'
import CRUD, { presenter, header, form, crud } 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 { queryBigItemByStationType } from '@/api/bomAccount'
import { formatDate } from '@/utils/commonUtils'

const defaultForm = {
  id: null,
  stationType: null,
  date: null,
  bigItemId: null,
  orderQuantity: null,
  status: null,
  startNumber: null,
  endNumber: null,
  description: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  deptId: null
}
export default {
  name: 'Spareparts',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['hy_status', 'station_type'],
  cruds() {
    return CRUD({
      title: '零件耗用',
      url: 'api/spareparts',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudSpareparts }
    })
  },
  data() {
    return {
      loading_add:false,
      collectFromFlag:false,
      collectFrom: { idno: null },
      bigItems: [],
      bigItemName: null,
      permission: {
        add: ['admin', 'spareparts:add'],
        edit: ['admin', 'spareparts:edit'],
        del: ['admin', 'spareparts:del'],
        hySpareParts: ['admin', 'spareparts:hySpareParts']
      },
      selectIds: {
        ids: []
      },
      hySparePartsDisabled:true,
      rules: {
        stationType: [
          { required: true, message: '请选择工位', trigger: 'blur' }
        ],
        bigItemId: [
          { required: true, message: '请选择型号品番', trigger: 'blur' }
        ],
        orderQuantity: [
          { required: true, message: '数量不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    //勾选
    selectData(selection, row) {
      this.hySparePartsDisabled= false
      if (selection.length === 0) {
        this.hySparePartsDisabled = true
      }
      selection.forEach((item) => {
          if (item.status != 'UN_CONSUME') {
            this.hySparePartsDisabled = false
          }
      })
    },
    //全选
    selectAllData(selection, row) {
      this.hySparePartsDisabled= false
      if (selection.length === 0) {
        this.hySparePartsDisabled = true
      }
      selection.forEach((item) => {
        if (item.status != 'UN_CONSUME') {
          this.hySparePartsDisabled = false
        }
      })
    },
    date(timestamp) {
      if (timestamp == null) {
        return null
      }
      // 创建Date对象并设置时间戳
      const dateObj = new Date(timestamp)
      // 提取年份、月份和日期
      const year = dateObj.getFullYear()
      const month = dateObj.getMonth() + 1 // JavaScript中月份从0开始计算，因此需加1
      const day = dateObj.getDate()
      return `${year}-${month}-${day}`
    },
    fromeClose() {
      this.bigItemName = null
    },
    getBigItem(dben) {
      this.bigItems = null
      queryBigItemByStationType(dben).then(res => {
        this.bigItems = res
      })
    },
    getBigItemName(dben) {
      this.bigItemName = dben
    },
    doXiuGai(dben) {
      this.getBigItem(dben.stationType)
      this.getBigItemName(dben.bigItemId.name)
      this.crud.toEdit(dben)
    },
    doShanChu(dben) {
      this.$confirm('此操作将删除此条数据, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.doDelete(dben)
      })

    },
    //批量新增
    collectFromBtn(){
      this.loading_add=true;
      autoAddHy(this.collectFrom.idno).then(res=>{
        this.$message.success(res);
        this.collectFrom.idno=null;
        this.loading_add=false;
        this.crud.toQuery()
      },e=>{
        this.loading_add=false;
      })
    },

    hySparePartsBtn(data){
      let data_ = this.selectIds;
      data_.ids = data.map(v => v.id);
      console.log(data_)
      hySpareParts(data_).then(res=>{
        this.$message.success(res);
        this.crud.toQuery()
      })
    },
    //日期格式化
    getFormatDate(data) {
      return formatDate(data)
    }
  }
}
</script>

<style scoped>

</style>
