<template>
  <div>
      <div class="my-title">{{ isEdit ? '编辑' : '新增' }}</div>
      <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="techName">
              <el-input
                v-model="dataForm.techName"
                :disabled="display || isEdit"
                placeholder="工艺名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺版本" prop="techVersion">
              <el-input
                v-model="dataForm.techVersion"
                :disabled="display || isEdit"
                placeholder="工艺版本"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料" prop="productId">
              <el-select
                v-model="dataForm.productId"
                :disabled="display || isEdit"
                remote
                filterable
                placeholder="请选择"
                style="width:100%"
                @change="productIdChangeHandle"
              >
                <el-option
                  v-for="item in optionLevel"
                  :key="item.productId"
                  :label="item.productNameStr"
                  :value="item.productId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注说明">
          <el-input
            v-model="dataForm.notes"
            :disabled="display || isEdit"
            placeholder="备注说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="" label-width="0px">
          <upload-component
            :display="display"
            :display-star="false"
            :title="'附件'"
            :accept="'*'"
            :file-obj-list="fileList"
            @uploadSuccess="uploadSuccess"
          />
        </el-form-item>
        <el-form-item label="工艺步骤" prop="nodeList"> </el-form-item>
        <el-row
          class="my-row"
          style="height: 350px; background-color: #efefef;"
        >
          <work-flow
            ref="workFlow"
            :nodeData="workFlowData"
            @saveWorkFlow="saveWorkFlow"
            :isEdit="isEdit"
            @dataChange="workFlowDataChange"
          ></work-flow>
        </el-row>
        <div style="margin-top:10px; border:1px solid #ccc; padding:5px">
          <div>
            <el-button @click="refreshTable">表格刷新</el-button>
          </div>
          <el-table :data="workFlowTableData">
            <el-table-column prop="nodeName" label="节点名称"></el-table-column>
            <el-table-column prop="workTypeName" label="工种类型"></el-table-column>
            <el-table-column prop="require" label="工序要求"></el-table-column>
            <el-table-column prop="explain" label="工序说明"></el-table-column>
            <el-table-column prop="process" label="工序特性"></el-table-column>
            <el-table-column prop="notes" label="备注"></el-table-column>
          </el-table>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onChose">取消</el-button>
        <el-button v-if="!display" type="primary" @click="dataFormSubmit()"
          >确定</el-button
        >
      </span>
    <!-- </el-dialog> -->
  </div>
</template>

<script>
import { getInfo, getProduct, getWorkType } from '@/api/crafts'
import UploadComponent from '../common/upload-component'
import WorkFlow from '@/components/work-flow/home'
// import data from "@/components/work-flow/config/data.json";
import { GenNonDuplicateID } from '@/components/work-flow/until'
export default {
  name: 'add-or-update',
  components: { UploadComponent, WorkFlow },
  computed: {
    orgId: {
      get () {
        return this.$store.state.user.orgId
      }
    }
  },
  data () {
    return {
      datas: {},
      visible: false,
      display: false,
      isEdit: false, // 是否是编辑页面
      isCopy: false,
      fileList: [],
      dataList: [],
      id: 0,
      dataForm: {
        techName: '',
        techVersion: '',
        productId: '',
        notes: ''
      },
      previewPath: '',
      previewName: '',
      previewVisible: false,
      optionsProducts: [],
      optionLevel: [],
      workFlowData: {
        nodeList: [],
        lineList: []
      }, // 流程图数据
      // 工艺流程表格数据
      workFlowTableData: [],
      // 工种列表
      workTypeOptions: [],
      dataRule: {
        techName: [
          { required: true, message: '工艺名称不能为空', trigger: 'blur' }
        ],
        techVersion: [
          { required: true, message: '工艺版本不能为空', trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '物料不能为空', trigger: 'change' }
        ]
      },
      dataRule1: {
        name: [
          { required: true, message: '节点名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '节点类型不能为空', trigger: 'change' }
        ],
        workTypeId: [
          { required: true, message: '工种不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.initNode()
  },
  mounted () {
    this.initNode()
  },
  methods: {
    onChose () {
      this.$emit('onChose')
    },
    initNode () {
      // this.workFlowData = data;
    },
    resetWorkFlow () {
      this.workFlowData = {
        nodeList: [],
        lineList: []
      }
    },
    async init (id, display, isEdit, isCopy) {
      this.fileList = []
      this.dataForm = {
        techName: '',
        techVersion: '',
        productId: '',
        notes: ''
      }
      this.visible = true
      this.display = display
      this.isEdit = isEdit && !isCopy
      this.isCopy = isCopy

      await getProduct({ current: 1, size: 20000 }).then(({ data }) => {
        if (data && data.code === '200') {
          this.optionLevel = data.data.records
          this.optionLevel.forEach(item => {
            item.productNameStr = item.productName + '-' + item.mapNumber + '-' + (item.techId && item.techId !== 0 ? '有' : '无')
          })
        }
      })
      if (!id) return
      await getInfo(id).then(async ({ data }) => {
        if (data && data.code === '200') {
          this.dataForm = data.data
          // 附件
          if (data.data.attachList) {
            data.data.attachList.forEach(item => {
              this.fileList.push({
                name: item.fileName,
                url: item.url,
                id: item.url
              })
            })
          }
          // 工艺流程
          this.workFlowData = {
            nodeList: data.data.nodeList,
            lineList: data.data.lineList
          }
        }
      })

      this.refreshTable()
    },
    productIdChangeHandle (val) {
      if (val) {
        let item = this.optionLevel.find(t => t.productId === val)
        this.dataForm.techName = item.productName
      }
      console.log(111, val)
    },
    handleRemove (file, fileList) {
      this.fileList = fileList
    },
    handleChange (file, fileList) {
      this.fileList = fileList
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    validateField (type) {
      this.$refs.dataForm.validateField(type)
    },
    // 表单提交
    dataFormSubmit () {
      let flowData = this.$refs.workFlow.getFlowData()
      if (!flowData) {
        this.$message.error('请先完成流程图！')
        return
      }

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // 填充附件
          let fList = this.fileList
          if (fList.length > 0) {
            this.dataForm.attachList = []
            for (let i = 0; i < fList.length; i++) {
              this.dataForm.attachList.push({
                fileName: fList[i].name,
                url: fList[i].url
              })
            }
          }

          let url = `/biz-service/technology/submit`
          if (this.isEdit && !this.isCopy) {
            url = `/biz-service/technology/update`
          }

          if (this.isCopy) {
            this.dataForm.id = 0
            this.dataForm.techId = null

            if (flowData.nodeList != null && flowData.nodeList.length > 0) {
              for (let index = 0; index < flowData.nodeList.length; index++) {
                let oldId = flowData.nodeList[index].id
                let newId = GenNonDuplicateID(8)
                flowData.nodeList[index].techId = null
                flowData.nodeList[index].id = newId

                if (flowData.lineList != null && flowData.lineList.length > 0) {
                  for (let index = 0; index < flowData.lineList.length; index++) {
                    flowData.lineList[index].techId = null
                    flowData.lineList[index].id = GenNonDuplicateID(8)
                    let from = flowData.lineList[index].from
                    let to = flowData.lineList[index].to
                    if (from === oldId) {
                      flowData.lineList[index].from = newId
                    }
                    if (to === oldId) {
                      flowData.lineList[index].to = newId
                    }
                  }
                }
              }
            }
          }

          this.$http({
            url: this.$http.adornUrl(url),
            method: 'post',
            data: this.$http.adornData({
              ...this.dataForm,
              ...flowData
            })
          }).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.resetWorkFlow()
                  this.onChose()
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    uploadSuccess (fileList) {
      this.fileList = fileList
    },
    // 保存流程图
    saveWorkFlow (workFlowData) {
      console.log('save work flow.')
      this.workFlowData = workFlowData
    },
    handleClose () {
      // this.visible = false
      this.$emit('close')
    },
    // 流程图数据变更通知
    workFlowDataChange () {
      this.refreshTable()
    },
    // 刷新表格
    async refreshTable () {
      this.workFlowTableData = []

      await this.getWorkTypeOptions()

      let flowData = this.$refs.workFlow.getFlowData()

      flowData.nodeList.forEach(item => {
        let workType = this.workTypeOptions.find(t => t.typeId === item.workTypeId)
        if (workType) {
          item.workTypeName = workType.name
        }
        this.workFlowTableData.push(item)
      })
    },
    async getWorkTypeOptions () {
      this.workTypeOptions = []
      await getWorkType().then(({ data }) => {
        if (data && data.code === '200') {
          this.workTypeOptions = data.data
          console.log(data.data)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.super-flow__node {
  .flow-node {
    > header {
      font-size: 14px;
      height: 32px;
      line-height: 32px;
      padding: 0 12px;
      color: #ffffff;
    }

    > section {
      text-align: center;
      line-height: 20px;
      overflow: hidden;
      padding: 6px 12px;
      word-break: break-all;
    }

    &.flow-node-start {
      > header {
        background-color: #55abfc;
      }
    }

    &.flow-node-condition {
      > header {
        background-color: #bc1d16;
      }
    }

    &.flow-node-approval {
      > header {
        background-color: rgba(188, 181, 58, 0.76);
      }
    }

    &.flow-node-cc {
      > header {
        background-color: #30b95c;
      }
    }

    &.flow-node-end {
      > header {
        height: 50px;
        line-height: 50px;
        background-color: rgb(0, 0, 0);
      }
    }
  }
}
</style>
