<template>
  <div class="production">
    <el-dialog
      title="排产模板详情"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="auto"
      >
        <el-row class="my-row">
          <el-col :span="8">
            <el-form-item label="产品" prop="productId">
              <el-select
                v-model="dataForm.productId"
                :disabled="display"
                @change="productChange"
                remote
                placeholder="请选择"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="mouldName">
              <el-input
                placeholder="请输入模板名称"
                v-model="dataForm.mouldName"
                maxlength="30"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          class="my-row"
          style="height: 350px; background-color: #efefef;"
        >
          <work-flow
            ref="workFlow"
            :nodeData="workFlowData"
            :selectOperator="true"
            @saveWorkFlow="saveWorkFlow"
          ></work-flow>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确认提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMouldDetail,
  getProductList,
  getMouldDetailByProductId,
  saveProdProductionMould,
  updateProdProductionMould
} from '@/api/production'
import { workTypeMasterList } from '@/api/worktype'
import WorkFlow from '@/components/work-flow/home'
export default {
  name: 'scheduling-details',
  components: {
    WorkFlow
  },
  data () {
    return {
      mouldId: '',
      visible: false,
      dataForm: {
        mouldName: ''
      },
      operatorList: [],
      operatorIds: [],
      productList: [],
      display: false,
      datas: {},
      workFlowData: {
        nodeList: [],
        lineList: []
      },
      // 是否点击了流程图保存按钮
      clickFlowSave: false,
      dataRule: {
        mouldName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ]
      },
      dataRule1: {
        operatorIds: [
          { required: true, message: '操作人员不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 初始化产品名称列表
    async initProductList () {
      getProductList().then(({ data }) => {
        if (data && data.code === '200') {
          data.data.forEach(item => {
            this.productList.push(item)
          })
        }
      })
    },
    // 初始化表单
    async init (id, disable) {
      this.visible = true
      this.display = disable
      this.mouldId = id
      if (!disable) {
        await this.initProductList()
      }

      await getMouldDetail(id).then(async ({ data }) => {
        if (data && data.code === '200') {
          this.dataForm = data.data
        }
      })
    },
    // 根据产品ID查询步骤详情
    async productChange (productId) {
      getMouldDetailByProductId(productId).then(async ({ data }) => {
        if (data && data.code === '200') {
          this.dataForm = {
            ...this.dataForm
          }
          // 流程图展示
          this.workFlowData = {
            nodeList: data.data.nodeList,
            lineList: data.data.lineList
          }
        }
      })
    },
    // 按工种ID查询操作人列表
    getOperatorList (workTypeId) {
      workTypeMasterList(workTypeId).then(({ data }) => {
        if (data && data.code === '200') {
          this.operatorList = []
          data.data.forEach(item => {
            this.operatorList.push(item)
          })
        }
      })
    },
    dataFormSubmit () {
      if (!this.clickFlowSave) {
        this.$message.error('请先点击流程图保存按钮！')
        return
      }

      if (
        !this.workFlowData ||
        this.workFlowData.nodeList.length === 0 ||
        this.workFlowData.lineList.length === 0
      ) {
        this.$message.error('请先完成流程图！')
        this.clickFlowSave = false
        return
      }

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // eslint-disable-next-line no-unused-vars
          let productionPlanNodes = []
          for (
            let index = 0;
            index < this.workFlowData.nodeList.length;
            index++
          ) {
            const node = this.workFlowData.nodeList[index]
            if (node.type !== 'end' && node.operatorId === '') {
              this.$message.error(`请选择 ${node.nodeName} 的操作人员！`)
              this.clickFlowSave = false
              return
            }
            productionPlanNodes.push({
              techNodeId: node.id,
              operatorId: node.operatorId
            })
          }

          let submitData = {
            mouldName: this.dataForm.mouldName,
            productId: this.dataForm.productId,
            nodeList: productionPlanNodes
          }

          if (this.mouldId === 0) {
            // 新增
            saveProdProductionMould(submitData)
              .then(({ data }) => {
                if (data && data.code === '200') {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.$emit('refreshDataList')
                      this.visible = false
                    }
                  })
                } else {
                  this.clickFlowSave = false
                  this.$message.error(data.msg)
                }
              })
              .catch(() => {
                this.clickFlowSave = false
              })
          } else {
            // 更新
            submitData.mouldId = this.mouldId
            updateProdProductionMould(submitData)
              .then(({ data }) => {
                if (data && data.code === '200') {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.$emit('refreshDataList')
                      this.visible = false
                    }
                  })
                } else {
                  this.clickFlowSave = false
                  this.$message.error(data.msg)
                }
              })
              .catch(() => {
                this.clickFlowSave = false
              })
          }
        }
      })
    },
    // 保存流程图
    saveWorkFlow (workFlowData) {
      this.clickFlowSave = true
      this.workFlowData = workFlowData
    }
  }
}
</script>

<style scoped></style>
