<template>
  <div class="production">
    <!-- <el-dialog
      :title="dialogTitle"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleClose"
    > -->
      <div class="my-title">{{ dialogTitle }}</div>
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="auto"
      >
        <el-row class="my-row" :gutter="20">
          <el-col :span="8">
            <el-form-item label="物料" prop="productId">
              <el-input v-if="disable && productName" :disabled="disable" v-model="productName"></el-input>
              <el-select
                v-else
                v-model="dataForm.productId"
                @change="productChange"
                remote
                :disabled="disable"
                placeholder="请选择"
                style="width:100%"
              >
                <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="10">
            <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"
            :isEdit="true"
          ></work-flow>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onChose">取消</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,
      dialogTitle: '',
      dataForm: {
        mouldName: ''
      },
      operatorList: [],
      operatorIds: [],
      productList: [],
      disable: false,
      productName: '',
      datas: {},
      workFlowData: {
        nodeList: [],
        lineList: []
      },
      dataRule: {
        mouldName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ]
      },
      dataRule1: {
        operatorIds: [
          { required: true, message: '操作人员不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    onChose () {
      this.$emit('onChose')
    },
    // 初始化物料名称列表
    async initProductList () {
      getProductList().then(({ data }) => {
        if (data && data.code === '200') {
          data.data.forEach(item => {
            this.productList.push(item)
          })
        }
      })
    },
    // 初始化表单
    async init (id, disable, productName) {
      this.disable = disable
      this.dialogTitle = disable ? '编辑排产模板' : '新增排产模板'
      this.mouldId = id
      this.productName = productName
      this.visible = true

      if (!disable) {
        await this.initProductList()
      }

      if (id > 0) {
        await getMouldDetail(id).then(async ({ data }) => {
          if (data && data.code === '200') {
            this.dataForm = data.data
            // 流程图展示
            this.workFlowData = {
              nodeList: data.data.nodeList,
              lineList: data.data.lineList
            }
          }
        })
      }
      // if (productionId && productionId > 0) {
      //   this.productChange(productionId)
      // }
    },
    // 根据物料ID查询步骤详情
    async productChange (productId) {
      this.$confirm('选中后不可更改，是否选择该物料？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.disable = true
        getMouldDetailByProductId(productId).then(async ({ data }) => {
          if (data && data.code === '200') {
            this.dataForm = {
              ...this.dataForm
            }
            // 流程图展示
            this.workFlowData = {
              nodeList: data.data.nodeList,
              lineList: data.data.lineList
            }
          } else {
            this.$message({
              type: 'error',
              message: data.msg
            })
          }
        })
      }).catch(() => {
        this.dataForm.productId = ''
      })
    },
    // 按工种ID查询操作人列表
    getOperatorList (workTypeId) {
      workTypeMasterList(workTypeId).then(({ data }) => {
        if (data && data.code === '200') {
          this.operatorList = []
          data.data.forEach(item => {
            this.operatorList.push(item)
          })
        }
      })
    },
    dataFormSubmit () {
      let flowData = this.$refs.workFlow.getFlowData()
      if (!flowData) {
        this.$message.error('请先完成流程图！')
        return
      }

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // eslint-disable-next-line no-unused-vars
          let productionPlanNodes = []
          for (
            let index = 0;
            index < flowData.nodeList.length;
            index++
          ) {
            const node = flowData.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,
              planCompletionTime: node.planCompletionTime
            })
          }

          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.onChose()
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(data.msg)
                }
              })
              .catch(() => {
              })
          } else {
            // 更新
            submitData.mouldId = this.mouldId
            updateProdProductionMould(submitData)
              .then(({ data }) => {
                if (data && data.code === '200') {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.onChose()
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(data.msg)
                }
              })
              .catch(() => {
              })
          }
        }
      })
    },
    handleClose () {
      this.$emit('close')
    }
  }
}
</script>

<style scoped></style>
