<template>
  <div>
    <el-card>
      <div style="width: 900px;margin: 0 auto">
        <span>机床名称：</span>
        <el-select v-model="machineValue" filterable clearable size="small" placeholder="机床名称" @change="getGroups">
          <el-option
            v-for="item in machineNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>分组名称：</span>
        <el-select v-model="groupValue" filterable clearable size="small" placeholder="分组名称">
          <el-option
            v-for="item in groupsNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-button :loading="listLoading" :disabled="disabled" type="primary" icon="el-icon-d-caret" size="small" style="margin-left: 10px" @click="transferData">传递</el-button>
        <el-button type="danger" icon="el-icon-delete" size="small" @click="allDelete">一键删除</el-button>
      </div>
    </el-card>
    <el-card>
      <el-table
        v-loading="listLoading"
        :data="tableData"
        :row-class-name="tableRowClassName"
        size="mini"
        border
        highlight-current-row
        @row-click="searchMaterial1">
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="50"/>
        <el-table-column align="center" label="物料状态" min-width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.物料流水号===null" type="warning" size="small">不存在</el-tag>
            <el-tag v-if="scope.row.物料流水号!==null" type="primary" size="small">存在</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="图号" min-width="200">
          <template slot-scope="scope">
            {{ scope.row.图号或者型号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.名称 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="材料" width="150">
          <template slot-scope="scope">
            {{ scope.row.材料或者规格 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="规格" width="100">
          <template slot-scope="scope">
            {{ scope.row.规格 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备件数量" width="100">
          <template slot-scope="scope">
            {{ scope.row.备件数量 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="装机数量" width="100">
          <template slot-scope="scope">
            {{ scope.row.装机数量 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="部件数量" width="100">
          <template slot-scope="scope">
            {{ scope.row.部件数量 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="制造商" min-width="200">
          <template slot-scope="scope">
            {{ scope.row.制造商 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="100">
          <template slot-scope="scope">
            {{ scope.row.备注 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="分类码" width="100">
          <template slot-scope="scope">
            {{ scope.row.分类码 }}
          </template>
        </el-table-column>
        <!--<el-table-column label="操作" fixed="right" align="center" width="200">-->
        <!--<template slot-scope="scope">-->
        <!--<el-button-->
        <!--size="mini"-->
        <!--type="primary"-->
        <!--icon="el-icon-edit"-->
        <!--@click="handleEdit(scope.row)">编辑</el-button>-->
        <!--<el-button-->
        <!--size="mini"-->
        <!--type="danger"-->
        <!--icon="el-icon-delete"-->
        <!--@click="handleDelete(scope.row)">删除</el-button>-->
        <!--</template>-->
        <!--</el-table-column>-->
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          :current-page="pageCurrent"
          :page-sizes="[10, 20, 40, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    <el-card>
      <el-table
        :data="tableData10"
        :cell-class-name="cell"
        style="width: 100%"
        size="mini"
        highlight-current-row
        border>
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="50"/>
        <el-table-column align="center" label="物料名称">
          <template slot-scope="scope">
            {{ scope.row.物料名称 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="物料规格">
          <template slot-scope="scope">
            {{ scope.row.物料规格 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="物料型号">
          <template slot-scope="scope">
            {{ scope.row.物料型号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="供货商">
          <template slot-scope="scope">
            {{ scope.row.供货商 }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center style="min-height: 300px" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="110px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="图号" prop="图号或者型号">
              <el-input
                v-model="form.图号或者型号"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="名称">
              <el-input
                v-model="form.名称"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="type === 1" label="材料" prop="材料">
              <el-select v-model="form.材料流水号" filterable clearable size="small" placeholder="机床名称">
                <el-option
                  v-for="item in materials"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item v-if="type === 2" label="规格" prop="规格">
              <el-input
                v-model="form.规格"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件数量" prop="数量">
              <el-input
                v-model.number="form.备件数量"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="装机数量" prop="数量">
              <el-input
                v-model.number="form.装机数量"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部件数量" prop="数量">
              <el-input
                v-model.number="form.部件数量"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="制造商" prop="供货商">
              <el-input
                v-model.number="form.制造商"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类码" prop="分类码">
              <el-input
                v-model.number="form.分类码"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="备注">
              <el-input
                v-model.number="form.备注"
                type="textarea"
                size="small"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button v-show="title==='编辑零件信息'" type="primary" @click="submitEdit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sleep } from '../../../utils/tool'
import { unSpecificationQuery, unSpecificationQueryWB, specificationQueryWB, specificationQuery, deleteBasicParts, deleteBWParts, getMaterial, getMaterialWB, searchMaterialWB, updateRow, updateRowWB, transferMX, transferWG, allDelete, searchMaterial1 } from '../../../api/TechnologyCenter/ImportParts'
export default {
  name: 'SpecificationData',
  props: {
    groupsNames: {
      type: Array,
      default: () => []
    },
    machineNames: {
      type: Array,
      default: () => []
    },
    projectName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      componentNum: '',
      groupValue: '',
      machineValue: '',
      tableData: [],
      tableDataAll: [],
      tableData10: [],
      listLoading: false,
      unSpecification: [],
      pageCurrent: 1,
      pageSize: 10,
      total: 0,
      title: '',
      materials: [],
      dialogFormVisible: false,
      type: 0, // 零件类型 暂定1为基本件，2为外购件和标准件
      form: {
        id: '',
        物料物流号: null, //  当基本件时使用材料流水号，外购件和标准件时，使用物料流水号
        物料名称: '',
        材料流水号: null,
        图号或者型号: '',
        名称: '',
        材料或者规格: '',
        规格: '',
        备件数量: '',
        装机数量: '',
        部件数量: '',
        制造商: '',
        备注: '',
        分类码: ''
      },
      err: 0,
      dialogFormVisibleWB: false,
      MaterialData: [],
      inputMaterial: '',
      rules: {
      },
      rulesWB: {
      },
      pageCurrentMaterial: 1,
      pageSizeMaterial: 10,
      totalMaterial: 0,
      loadingMaterial: false
    }
  },
  computed: {
    disabled() {
      if (this.tableDataAll.length === 0) {
        return true
      }
      if (this.unSpecification.data) {
        return this.unSpecification.data.length > 0
      }
      return true
    },
    materialName() {
      for (let i = 0; i < this.materials.length; i++) {
        if (this.materials[i].value === this.form.材料流水号) {
          return this.materials[i].label
        }
      }
    }
  },
  watch: {
    machineNames(val) {
      this.total = 0
      this.machineValue = val.length > 0 ? val[0].value : ''
      this.getGroups()
    },
    groupsNames(val) {
      this.groupValue = val.length > 0 ? val[0].value : ''
    },
    groupValue(val) {
      val ? this.fetchData() : this.tableData = []
    }
  },
  mounted() {
    this.getSelect(getMaterial, ['材料', '材料流水号'], 'materials')
  },
  methods: {
    cell({ row, column, rowIndex, columnIndex }) {
      if (row.对比类型 === 1 && columnIndex === 2) {
        return 'rgb196'
      }
      if (row.对比类型 === 2 && columnIndex === 1) {
        return 'rgb196'
      }
      if (row.对比类型 === 2 && columnIndex === 2) {
        return 'rgb196'
      }
      if (row.对比类型 === 3 && columnIndex === 1) {
        return 'rgb196'
      }
      if (row.对比类型 === 4 && columnIndex === 3) {
        return 'rgb196'
      }
      if (row.对比类型 === 5 && columnIndex === 1) {
        return 'rgb196'
      }
      if (row.对比类型 === 5 && columnIndex === 3) {
        return 'rgb196'
      }
      if (row.对比类型 === 6 && columnIndex === 2) {
        return 'rgb196'
      }
      if (row.对比类型 === 6 && columnIndex === 3) {
        return 'rgb196'
      }
    },
    async fetchData() {
      this.pageCurrent = 1
      this.tableData10 = []
      try {
        this.listLoading = true
        this.total = 0
        this.tableDataAll = []
        const projectCheck = this.projectName ? 1 : 0
        const machineCheck = this.machineValue ? 1 : 0
        const groupCheck = this.groupValue ? 1 : 0
        if (this.groupValue.indexOf('MX') > -1) { // 当分组为基本件时，查询基本件规范和不规范数据，否则查询外购件或标准件规范和不规范数据
          // 分别查出规范和不规范数据，将规范数据放前面在一个总数组中
          this.type = 1
          this.unSpecification = await unSpecificationQuery(projectCheck, this.projectName, machineCheck, this.machineValue, groupCheck, this.groupValue)
          this.unSpecification.data.forEach(item => {
            this.tableDataAll.push(item)
          })
          const specification = await specificationQuery(projectCheck, this.projectName, machineCheck, this.machineValue, groupCheck, this.groupValue)
          specification.data.forEach(item => {
            this.tableDataAll.push(item)
          })
        } else {
          this.type = 2
          this.unSpecification = await unSpecificationQueryWB(projectCheck, this.projectName, machineCheck, this.machineValue, groupCheck, this.groupValue)
          console.log(this.unSpecification)
          this.unSpecification.data.forEach(item => {
            this.tableDataAll.push(item)
          })
          const specification = await specificationQueryWB(projectCheck, this.projectName, machineCheck, this.machineValue, groupCheck, this.groupValue)
          specification.data.forEach(item => {
            this.tableDataAll.push(item)
          })
        }
        this.total = this.tableDataAll.length
        this.pagination(this.pageCurrent, this.pageSize) // 前端分页，数据很多生成DOM节点也多，分页效果很明显。
        this.listLoading = false
      } catch (e) {
        console.log(`查询零件发生错误：${e}`)
      }
    },
    allDelete() {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.projectName !== '' && this.machineValue !== '' && this.groupValue !== '') {
          allDelete(this.projectName, this.machineValue, this.groupValue).then(response => {
            if (response.data[0].result === '1') {
              this.tableData = []
              this.tableData10 = []
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          })
        } else {
          this.$message.warning('请选择好项目机床分组')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getGroups() {
      this.$emit('machineChange', this.machineValue)
    },
    pagination(pageCurrent, pageSize) {
      this.tableData = this.tableDataAll.slice((pageCurrent - 1) * pageSize, pageCurrent * pageSize)
    },
    tableRowClassName({ row }) {
      if (this.unSpecification.data.indexOf(row) > -1) {
        return 'warning-row'
      }
      return ''
    },
    handleEdit(row) {
      this.editForm(row, 'form', [this.title = '编辑零件信息', this.dialogFormVisible = true])
      if (this.type === 2) {
        this.form.物料名称 = row.材料或者规格
        this.form.物料流水号 = row.物料流水号
      }
    },
    submitEdit() {
      if (this.type === 1) {
        this.editTable(updateRow, [this.form.图号或者型号, this.form.名称, this.form.规格, this.materialName, this.form.备件数量, this.form.装机数量, this.form.制造商, this.form.备注, this.form.分类码, this.form.id, this.form.材料流水号, this.form.部件数量], 'form', function() {
          this.dialogFormVisible = false
          this.fetchData()
        })
      } else if (this.type === 2) {
        this.editTable(updateRowWB, [this.form.图号或者型号, this.form.名称, this.form.规格, this.form.物料名称, this.form.备件数量, this.form.装机数量, this.form.制造商, this.form.备注, this.form.分类码, this.form.id, this.form.物料流水号, this.form.部件数量], 'form', function() {
          this.dialogFormVisible = false
          this.fetchData()
        })
      } else {
        console.log(`编辑类型发生错误`)
      }
    },
    cancel() {
      this.dialogFormVisible = false
    },
    handleDelete(row) {
      if (this.type === 1) {
        this.deleteRow(deleteBasicParts, row.id, function() {
          this.fetchData()
        })
      } else {
        this.deleteRow(deleteBWParts, row.id, function() {
          this.fetchData()
        })
      }
    },
    searchMaterial1(row) {
      console.log(row)
      searchMaterial1(row.图号或者型号, row.名称, row.规格).then(response => {
        this.tableData10 = response.data
        console.log(response.data)
      })
    },
    getMaterialWB() {
      this.getTable(getMaterialWB, [this.pageCurrentMaterial, this.pageSizeMaterial], ['MaterialData', 'totalMaterial', 'loadingMaterial'])
    },
    searchMaterial() {
      this.getTable(searchMaterialWB, [this.inputMaterial, this.pageCurrentMaterial, this.pageSizeMaterial], ['MaterialData', 'totalMaterial', 'loadingMaterial'])
    },
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.pagination(this.pageCurrent, this.pageSize)
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.pagination(this.pageCurrent, this.pageSize)
    },
    handleSizeChangeMaterial(val) {
      this.pageCurrentMaterial = 1
      this.pageSizeMaterial = val
      this.getMaterialWB()
    },
    handleCurrentChangeMaterial(val) {
      this.pageCurrentMaterial = val
      this.getMaterialWB()
    },
    async transferData() {
      try {
        this.err = 0
        if (this.groupValue) {
          this.listLoading = true
          if (this.groupValue.indexOf('MX') > -1) {
            for (let i = 0; i < this.tableDataAll.length; i++) {
              const data = this.tableDataAll[i]
              console.log(data)
              const total = parseInt(data.备件数量) + parseInt(data.装机数量) * parseInt(data.部件数量)
              const resp = await transferMX(data.图号或者型号, data.名称, total, data.备注, data.标记, data.设计者编号, data.组件流水号, data.材料流水号, data.规格, 1, data.是否传递, data.序号, data.id, data.备件数量)
              await sleep(10)
              if (resp.data[0].result === '0') {
                this.err++
              }
            }
          } else {
            for (let i = 0; i < this.tableDataAll.length; i++) {
              let dataType
              const data = this.tableDataAll[i]
              const total = parseInt(data.备件数量) + parseInt(data.装机数量) * parseInt(data.部件数量)
              if (this.groupValue.indexOf('WG') > -1) {
                dataType = 2
              } else {
                dataType = 1
              }
              const resp = await transferWG(data.组件流水号, data.物料流水号, total, data.备注, data.标记, data.设计者编号, data.是否传递, dataType, data.序号, data.id, data.备件数量)
              await sleep(10)
              if (resp.data[0].result === '0') {
                this.err++
                this.$notify.error(`传递零件失败`)
              }
            }
          }
          if (this.err === 0) { // 传递成功后，清除该分组。当所有组都传递完成后，该项目下的机床和分组消失
            console.log(this.groupsNames.indexOf(this.groupValue), 22222)
            // const index = this.groupsNames.indexOf(this.groupValue)
            // this.groupsNames.splice(index, 1)
            if (this.groupsNames.length === 0) {
              const groupIndex = this.machineNames.indexOf(this.machineValue)
              this.machineNames.splice(groupIndex, 1)
            }
            this.$message.success(`传递成功`)
            this.tableDataAll = []
            this.tableData = []
            this.tableData10 = []
          } else {
            this.$message.error(`${this.err}个零件传递失败`)
          }
          this.listLoading = false
        } else {
          this.$message.warning(`请选择分组传递`)
        }
      } catch (e) {
        this.$message.error(`传递发生错误`)
        console.log(`${e}`)
      }
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }
  .rgb196{
    background: palevioletred;
  }
</style>

<style scoped>
  span{
    margin: 10px;
  }
</style>
