<template>
  <div class="app-container">
    <el-card>
      <span>零件号:</span>
      <el-input v-model="partNumber" size="small" placeholder="零件号" clearable style="width:200px"/>
      <el-button type="primary" size="mini" icon="el-icon-search" style="margin-left:10px" plain @click="getList()">查询</el-button>
      <el-button type="danger" plain size="mini" icon="el-icon-caret-right" style="float: right;margin-right:10px" @click="getBack()">打回车间</el-button>
      <el-table v-loading="loading1" ref="multipleTable" :data="List1" border size="mini" stripe highlight-current-row height="265" style="width: 100%;margin-top: 20px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="项目名称" prop="项目名称" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.项目名称 }}
          </template>
        </el-table-column>
        <el-table-column label="零件图号" prop="零件图号" align="center" min-width="200px" >
          <template slot-scope="scope">
            {{ scope.row.零件图号 }}
          </template>
        </el-table-column>
        <el-table-column label="零件名称" prop="零件名称" align="center" min-width="100px" >
          <template slot-scope="scope">
            {{ scope.row.零件名称 }}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="100px" >
          <template slot-scope="scope">
            {{ scope.row.批次数量 }}
          </template>
        </el-table-column>
        <el-table-column label="外协工序" align="center" show-overflow-tooltip min-width="150px">
          <template slot-scope="scope">
            {{ scope.row.外协工序 }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card>
      <el-col :span="8">
        <el-input v-model="manufacturers" size="small" placeholder="外协厂家" style="width:160px" clearable @keyup.enter.native="pageSize=20;pageList=1;fetchData()" @clear="pageSize=20;pageList=1;fetchData()"/>
        <el-button type="primary" size="mini" icon="el-icon-search" style="margin-left:10px" plain @click="pageSize=20;pageList=1;fetchData()">查询</el-button>
        <el-checkbox v-model="isChecked" size="small" label="历史"/>
        <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" style="margin-left:1px" @click="handleAdd()">新增</el-button>
        <el-table v-loading="loading2" :data="List" highlight-current-row height="450" size="mini" stripe border @row-click="searchProcess" >
          <el-table-column label="表单号" prop="表单号" align="center" min-width="155px">
            <template slot-scope="scope">
              {{ scope.row.表单号 }}
            </template>
          </el-table-column>
          <el-table-column label="外协厂家" prop="外协厂家" align="center" min-width="140px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.外协厂家 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100px">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-edit" plain style="margin-left:10px" @click="handleEdit(scope.row)"/>
              <el-button :disabled="scope.row.单据状态==='成交'" plain type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-top: 10px;">
          <el-pagination
            v-show="!loading2"
            :current-page="currentPage"
            :page-sizes="[20, 30, 40]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </el-col>
      <el-col :span="16">
        <div>
          <el-button type="warning" size="mini" icon="el-icon-arrow-down" style="margin-top:3px" plain @click="getSpareParts">选入零件</el-button>
          <el-button type="primary" size="mini" icon="el-icon-download" style="margin-left:10px;margin-top: 3px;float: right" plain @click="exportTable('RWD')">导出任务单</el-button>
          <el-tooltip :open-delay="1200" effect="dark" content="成交" placement="top">
            <el-button type="success" size="mini" icon="el-icon-success" style="margin-left:10px;margin-top: 3px;float: right" plain @click="Deal">提交</el-button>
          </el-tooltip>
          <el-tooltip :open-delay="1200" effect="dark" content="核对价格信息后确定" placement="top">
            <el-button type="success" size="mini" icon="el-icon-edit" style="margin-left:10px;margin-top: 3px;float: right" plain @click="confirmPrice">保存</el-button>
          </el-tooltip>
        </div>
        <el-table v-loading="loading" :data="List3" :summary-method="getSummaries" height="488" size="mini" show-summary border>
          <el-table-column label="零件图号" align="center" min-width="150px">
            <template slot-scope="scope">
              {{ scope.row.零件图号 }}
            </template>
          </el-table-column>
          <el-table-column label="零件名称" align="center" min-width="120px">
            <template slot-scope="scope">
              {{ scope.row.零件名称 }}
            </template>
          </el-table-column>
          <el-table-column label="外协工序" align="center" min-width="120px">
            <template slot-scope="scope">
              {{ scope.row.外协工序 }}
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="60px">
            <template slot-scope="scope">
              {{ scope.row.批次数量 }}
            </template>
          </el-table-column>
          <el-table-column label="外协价格" align="center" width="130px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.加工价格_成交" size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="机加工开始时间" align="center" width="150px">
            <template slot-scope="scope">
              {{ scope.row.机加工开始时间 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80px">
            <template slot-scope="scope">
              <el-button size="mini" type="text" plain icon="el-icon-right" @click="handleDelete1(scope.row)">移出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-card>

    <el-dialog v-el-drag-dialog :title="title" :visible.sync="dialogFormVisible" center style="min-height: 300px" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="100px" class="demo-ruleForm">
        <el-form-item label="表单号" prop="表单号" style="margin-left: 70px">
          <el-input v-model="form.表单号" placeholder="表单号" size="small" style="width: 200px" disabled/>
        </el-form-item>
        <el-form-item label="下达任务日期" prop="下达任务日期" style="margin-left: 70px">
          <el-date-picker
            v-model="form.下达任务日期"
            type="date"
            size="small"
            style="width:200px"
            disabled
            default-value
            placeholder="下达任务日期"
            value-format="yyyy-MM-dd"/>
        </el-form-item>
        <el-form-item label="外协厂家" prop="外协厂家" style="margin-left: 70px">
          <el-select v-model="form.外协厂家" placeholder="选择外协厂家" filterable clearable size="small" style="width:200px">
            <el-option
              v-for="item in ManufacturerName"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-show="false" label="运费" prop="运费" style="margin-left: 70px">
          <el-input v-model="form.运费" placeholder="运费" size="small" style="width:200px" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="callOff('form')">取消</el-button>
        <el-button type="primary" @click="submit('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { initOutHelp, getTable, getTable1, addTable, editData, deleteData, insertParts, getParts, getPrice, editData1, deleteData1, getNumber, getBack } from '@/api/Outsourcing/OutsourcingTaskExecution'
import { mapGetters } from 'vuex'
import elInput from 'element-ui/packages/input'

export default {
  components: {
    elInput
  },
  data() {
    return {
      工艺计划流水号: [],
      isChecked: false,
      bianliang: [],
      card: false,
      费用: '',
      加工价格合计: 0,
      材料价格合计: 0,
      其他价格合计: 0,
      运费: 0,
      总计: 0,
      大写金额: '',
      任务单号: '',
      任务下达日期: '',
      外协厂家: '',
      外协员: '',
      外协员电话: '',
      联系人: '',
      联系人电话: '',
      最早时间: '',
      最晚时间: '',
      // 以上是新增的
      loading: false,
      loading1: false,
      loading2: false,
      num: null,
      num1: null,
      num2: null,
      num3: null,
      name1: '',
      time: '',
      time1: '',
      time2: '',
      input: '',
      contrast: 3000000000000,
      contrast1: 0,
      param: 0,
      partNumber: '',
      processingPrice: null,
      materialPrice: null,
      formNumber: '',
      coOperationProcess: [],
      ManufactorNumber: null,
      ManufactorNumber1: null,
      manufacturers: '',
      dialogFormVisible: false,
      data2: [],
      List: [],
      money: null,
      sum: 0,
      num10: [],
      title: '',
      result: 0,
      documentStatus: null,
      sign: null,
      Number: '',
      form: {
        表单号: '',
        下达任务日期: '',
        外协厂家: '',
        运费: null
      },
      ManufacturerName: [], // 厂家名称
      rules: {
        外协厂家: [{ required: true, message: '请选择外协厂家', trigger: 'change' }],
        运费: [{ required: true, message: '请输入运费', trigger: 'blur' }]
      },
      code: 0,
      code1: 0,
      processNum: [],
      single: null,
      procedure: [],
      List1: [],
      List2: [],
      List3: [],
      Explain: '',
      freight: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      process: [[]],
      returns: [],
      零件图号: [],
      零件名称: [],
      批次数量: [],
      外协预算总价格: [],
      加工价格_成交: [],
      外协分类: [],
      材料费: [],
      材料价格_价格: [],
      其他价格: [],
      机加工开始时间: [],
      机加工结束时间: [],
      外协加工任务单明细流水号: [],
      total: null, // 总条数
      pageSize: 20, // 每页显示条数
      pageList: 1, // 后台获取页
      currentPage: 1, // 显示当前页
      options: [{
        value: '1',
        label: '未成交'
      }, {
        value: '2',
        label: '成交'
      }]
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData()
    this.getList()
  },
  methods: {
    // 初始化查询
    fetchData() {
      this.ManufacturerName = []
      initOutHelp().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.ManufacturerName.push({
            label: response.data[i].外协厂家名称,
            value: response.data[i].外协厂家流水号
          })
        }
      })
      this.loading2 = true
      this.List = []
      this.List3 = []
      this.Number = ''
      this.manufacturers ? this.num1 = 1 : this.num1 = 0
      getTable(this.num1, this.manufacturers, this.isChecked, this.currentPage, this.pageSize).then(response => {
        this.total = parseInt(response.data.total)
        this.List = response.data.rows
      })
      this.loading2 = false
    },
    // 表3合计
    getSummaries(param) {
      const { data } = param
      const sums = ['', '', '', 0, 0, '']
      sums[0] = '合计'
      for (let i = 0; i < data.length; i++) {
        sums[3] += parseInt(data[i].批次数量)
      }
      for (let i = 0; i < data.length; i++) {
        sums[4] += Math.round(parseFloat(data[i].加工价格_成交) * 100) / 100
      }
      sums[4] = Math.round(sums[4] * 100) / 100 + ' 元'
      return sums
    },
    // 查询未选入零件
    getList() {
      this.partNumber ? this.check = 1 : this.check = 0
      this.loading1 = true
      this.List1 = []
      getTable1(this.check, this.partNumber).then(response => {
        this.List1 = response.data
        this.loading1 = false
      })
    },
    // 表1多选
    handleSelectionChange(val) {
      this.processNum = val
      this.工艺计划流水号 = []
      for (let i = 0; i < val.length; i++) {
        this.工艺计划流水号.push(val[i].工艺计划流水号)
      }
    },
    // 点击表2 查询表3
    searchProcess(row) {
      this.loading = true
      this.List3 = []
      this.Number = row.外协加工任务单流水号
      this.ManufactorNumber = row.外协厂家流水号
      getParts(row.外协加工任务单流水号).then(response => {
        this.List3 = response.data
        this.loading = false
      })
    },
    // 新增外协任务单
    handleAdd() {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.title = '新增外协任务单'
      var time = new Date()
      var month = time.getMonth() + 1
      var day = time.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (day >= 1 && day <= 9) {
        day = '0' + day
      }
      this.form.下达任务日期 = time.getFullYear() + '/' + month + '/' + day
      getNumber(this.form.下达任务日期).then(response => {
        this.form.表单号 = response.data.result[0].Column1
      })
      this.form.运费 = 0
      this.form.外协厂家 = ''
      this.dialogFormVisible = true
    },
    // 编辑外协任务单
    handleEdit(row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.title = '编辑外协任务单'
      this.dialogFormVisible = true
      this.form.表单号 = row.表单号
      this.form.运费 = row.运费
      this.form.外协厂家 = row.外协厂家
      this.form.下达任务日期 = row.任务下达日期
      this.ManufactorNumber1 = row.外协厂家流水号
      this.Number = row.外协加工任务单流水号
      if (row.入库标志 === null) {
        this.sign = 1
      }
      if (row.单据状态 === '未成交') {
        this.documentStatus = 1
      } else {
        this.documentStatus = 2
      }
    },
    // 提交
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '新增外协任务单') {
            this.submitAdd()
          } else if (this.title === '编辑外协任务单') {
            this.submitEdit()
          }
        }
      })
    },
    // 关闭
    callOff(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // 提交新增
    submitAdd() {
      this.form.运费 = parseInt(this.form.运费)
      if (isNaN(this.form.运费)) {
        this.form.运费 = ''
        this.$message.error('请输入数字')
      } else {
        addTable(this.form.表单号, this.id, this.form.外协厂家, this.form.下达任务日期, this.form.运费).then(response => {
          if (response.data[0].result === '1') {
            this.$notify({
              title: '成功',
              message: '信息添加成功',
              type: 'success'
            })
            this.dialogFormVisible = false
            this.title = ''
            this.fetchData()
          } else {
            this.$message.error('信息添加失败')
          }
        })
      }
    },
    // 提交编辑
    submitEdit() {
      editData(this.Number, this.form.外协厂家, this.form.运费, this.Explain).then(response => {
        if (response.data[0].result === '1') {
          this.$message.success('编辑成功')
          this.dialogFormVisible = false
          this.title = ''
          this.fetchData()
        } else { this.$message.error('编辑失败') }
      })
    },
    // 删除任务单
    handleDelete(row) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteData(row.外协加工任务单流水号).then(response => {
          if (response.data[0].result === '1') {
            if (this.List && this.List.length === 1 && this.pageList > 1) { // 判断删除的是否是最后一页最后一行，如果是且不是第一页，页数减一
              this.pageList--
            }
            this.$message.success('删除成功')
            this.fetchData()
            this.getList()
            this.card = false
          } else { this.$message.error('删除失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打回车间
    getBack() {
      if (this.processNum.length !== 0) {
        this.result = 0
        for (let i = 0; i < this.processNum.length; i++) {
          getBack(this.processNum[i].工艺计划流水号).then(response => {
            this.result += parseInt(response.data[0].result)
            if (this.processNum.length === this.result) {
              this.$message.success('打回成功')
              this.getList()
            }
          })
        }
      } else {
        this.$message.warning('请勾选要打回的零件')
      }
    },
    // 选入零件
    getSpareParts() {
      if (this.Number) {
        insertParts(this.工艺计划流水号, this.Number).then(response => {
          this.loading = true
          this.List3 = []
          getParts(this.Number).then(response => {
            this.List3 = response.data
            this.loading = false
          })
        })
      } else {
        this.$message.warning('请选择订单')
      }
    },
    // 保存
    confirmPrice() {
      var 外协加工任务单明细流水号组 = []
      var 加工价格_成交组 = []
      for (let i = 0; i < this.List3.length; i++) {
        外协加工任务单明细流水号组.push(this.List3[i].外协加工任务单明细流水号)
        加工价格_成交组.push(this.List3[i].加工价格_成交)
      }
      getPrice(外协加工任务单明细流水号组, 加工价格_成交组).then(response => {
        this.loading = true
        this.List3 = []
        getParts(this.Number).then(response => {
          this.List3 = response.data
          this.loading = false
        })
      })
    },
    // 提交
    Deal() {
      this.$confirm('成交后单据不可修改, 确定成交吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        editData1(this.Number, this.ManufactorNumber).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('提交成功')
            this.fetchData()
          } else { this.$message.error('提交失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        })
      })
    },
    // 导出任务单
    exportTable() {
      if (!this.Number) {
        this.$message.warning('请选择外协加工任务单')
      } else {
        var param = []
        param[0] = ['外协加工任务单流水号', this.Number]
        var Data = this.CreateData('2001', '报表_外协加工任务单明细', param)
        this.exportExcel_NPOI(Data)
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageList = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageList = val
      this.fetchData()
    },
    // 移除
    handleDelete1(row) {
      this.$confirm('此操作将移除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteData1(row.外协加工任务单明细流水号).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('移除成功')
            this.getList()
            this.loading = true
            this.List3 = []
            getParts(this.Number).then(response => {
              this.List3 = response.data
              this.loading = false
            })
          } else { this.$message.error('移除失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
  .el-card{
    margin: 0px;
  }
  td{
    width: 100px;
    height: 30px;
    text-align:center;
  }
  .el-table .chengjiao {
    background: #AEF199;
  }
  .el-input__inner {
    height: 30px;
  }
</style>
<style>
  .el-table .chajia {
    background: #EBF953;
  }
  #tableHead td{
    border:1px solid black;
  }
  .tableData td{
    border:1px solid black;
  }
  #tableFoot td{
    border:1px solid black;
  }
  .tbodyHead td{
    text-align: left;
  }
  .foot td{
    width: 7%;
    text-align: left;
  }
</style>
