
<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" style="height: 350px; background-color: #efefef;">
          <super-flow
            v-if="visible"
            ref="superFlow"
            :node-list="nodeList"
            :link-list="linkList"
            :graph-menu="graphMenuList"
            :node-menu="nodeMenuList"
            :link-menu="linkMenuList"
            :link-desc="linkDesc">
          </super-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>

    <el-dialog
        :title="drawerConf.title"
        :visible.sync="drawerConf.visible"
        :close-on-click-modal="false"
        width="500px">
      <el-form
          @keyup.native.enter="settingSubmit"
          @submit.native.prevent
          v-show="drawerConf.type === drawerType.node"
          ref="nodeSetting"
          :rules="dataRule1"
          :model="nodeSetting">
        <el-row class="my-row">
          <el-col :span="24">
            <el-form-item
                label="节点名称"
                prop="name">
              <el-input
                  v-model="nodeSetting.name"
                  placeholder="请输入节点名称"
                  maxlength="30"
                  disabled>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="my-row" >
          <el-col :span="24" v-if="drawerConf.prop !== 'end'">
            <el-form-item
              label="操作人员"
              prop="operatorIds">
              <el-select
                v-model="nodeSetting.operatorIds"
                multiple
                style="width:100%"
                placeholder="请选择">
                <el-option
                  v-for="item in operatorList"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
          slot="footer"
          class="dialog-footer">
        <el-button
            @click="drawerConf.cancel">
          取 消
        </el-button>
        <el-button
            type="primary"
            @click="settingSubmit">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getStepId } from '@/api/crafts'
  import { getMonitoringDetail } from '@/api/production'
  import { uuid } from '../common/vue-super-flow/utils'
  const drawerType = {
    node: 0,
    link: 1
  }
  export default {
    name: 'recording-details',
    data () {
      return {
        mouldId: '',
        visible: false,
        dataForm: {},
        drawerType,
        operatorList: [],
        operatorIds: [],
        productList: [],
        display: false,
        drawerConf: {
          title: '',
          visible: false,
          prop: '',
          type: null,
          info: null,
          open: (type, info) => {
            if (info.meta.workTypeId && info.meta.prop !== 'end') {
              this.getOperatorList(info.meta.workTypeId);
            }
            
            const conf = this.drawerConf
            conf.visible = true
            conf.type = type
            conf.info = info
            if (conf.type === drawerType.node) {
              conf.title = '节点'
              conf.prop = info.meta.prop
              if (this.$refs.nodeSetting) this.$refs.nodeSetting.resetFields()
              this.$set(this.nodeSetting, 'name', info.meta.name)
              this.$set(this.nodeSetting, 'desc', info.meta.desc)
              // this.$set(this.nodeSetting, 'prop', info.meta.prop)
              this.$set(this.nodeSetting, 'type', info.meta.type)
              this.$set(this.nodeSetting, 'workTypeId', info.meta.workTypeId)
              this.$set(this.nodeSetting, 'operatorIds', info.meta.operatorIds)
              
            } else {
              conf.title = '连线'
              if (this.$refs.linkSetting) this.$refs.linkSetting.resetFields()
              // this.$set(this.linkSetting, 'desc', info.meta ? info.meta.desc : '')
            }
          },
          cancel: () => {
            this.drawerConf.visible = false
            if (this.drawerConf.type === drawerType.node) {
              this.$refs.nodeSetting.clearValidate()
            } else {
              this.$refs.linkSetting.clearValidate()
            }
          }
        },
        linkSetting: {
          desc: ''
        },
        nodeSetting: {
          name: '',
          desc: '',
          type: 1,
          workTypeId: ''
        },
        origin: [100, 100],
        nodeList: [],
        linkList: [],
        graphMenuList: [
          [
            {
              label: '开始节点',
              disable: true,
              selected: async (graph, coordinate) => {
                const start = graph.nodeList.find(node => node.meta.prop === 'start')
                let id = ''
                await getStepId().then(({ data }) => {
                  id = data.data.stepId
                })
                if (!start) {
                  graph.addNode({
                    width: 90,
                    height: 50,
                    coordinate: coordinate,
                    id: id,
                    meta: {
                      prop: 'start',
                      name: '开始节点'
                    }
                  })
                }
              }
            },
            {
              label: '节点',
              disable: true,
              selected: async (graph, coordinate) => {
                let id = ''
                await getStepId().then(({ data }) => {
                  id = data.data.stepId
                })
                graph.addNode({
                  width: 120,
                  height: 70,
                  coordinate: coordinate,
                  id: id,
                  meta: {
                    prop: 'condition',
                    name: '节点名称'
                  }
                })
              }
            },
            {
              label: '结束节点',
              disable: true,
              selected: async (graph, coordinate) => {
                let id = ''
                await getStepId().then(({ data }) => {
                  id = data.data.stepId
                })
                graph.addNode({
                  width: 90,
                  height: 50,
                  coordinate: coordinate,
                  id: id,
                  meta: {
                    prop: 'end',
                    name: '结束节点'
                  }
                })
              }
            }
          ],
          [
            {
              label: '完成',
              selected: (graph, coordinate) => {
                graph.selectAll()
                this.datas = graph
                console.log(graph)
              }
            }
          ]
        ],
        nodeMenuList: [
          // [
          //   {
          //     label: '删除',
          //     disable: true,
          //     hidden (node) {
          //       return node.meta.prop === 'start'
          //     },
          //     selected (node, coordinate) {
          //       node.remove()
          //     }
          //   }
          // ],
          // [
          //   {
          //     label: '编辑',
          //     selected: (node, coordinate) => {
          //       this.drawerConf.open(drawerType.node, node)
          //     }
          //   }
          // ]
        ],
        linkMenuList: [
          [
            {
              label: '删除',
              selected: (link, coordinate) => {
                link.remove()
              }
            }
          ]
        ],
        datas: {},
        dataRule: {
          mouldName: [{required: true, message: '请输入模板名称', trigger: 'blur'}]
        },
        dataRule1: {
           operatorIds: [{ required: true, message: '操作人员不能为空', trigger: 'change' }]
        }
      }
    },
    methods: {
      // 初始化表单
      async init (id, disable) {
        this.visible = true
        this.display = disable
        this.nodeList = []
        this.linkList = []
        this.mouldId = id;

        await getMonitoringDetail(id).then(async ({data}) => {
          if (data && data.code === '200') {
            this.dataForm = {...this.dataForm, proTechnologyStepList: data.data}
            console.log(this.dataForm.proTechnologyStepList)
            // 图纸
            if (this.dataForm.proTechnologyStepList) {
              const dataline = []
              const datanode = []
              await this.dataForm.proTechnologyStepList.forEach((v, i) => {
                // eslint-disable-next-line no-unused-vars
                const sortNo = []
                
                const datas = v.sort((a, b) => Number(a['sortNo']) - Number(b['sortNo']))
                let length = datas.length
                datas.forEach((item, index) => {
                  const find = datanode.find(map => map.id === item.stepId)
                  if (!find) {
                    datanode.push({
                      id: item.stepId,
                      // width: (index === 0 || item.workTypeId === '0') ? 140 : 180,
                      // height: (index === 0 || item.workTypeId === '0') ? 80 : 100,
                      width: 140,
                      height: 80,
                      coordinate: item.coordinate.split(','),
                      meta: {
                        name: item.stepName + (item.state === '0' ? '(已完成)' : '(未完成)'),
                        desc: item.operatorName,
                        prop: index === 0 ? 'start' : (index === length - 1) ? 'end' : 'condition',
                        notes: item.notes || '',
                        workTypeId: item.workTypeId || '',
                        type: item.type || '',
                        operatorIds: item.operatorId == null ? [] : item.operatorId.split(',')
                      }
                    })
                  }
                  const id = item.stepId
                  if ((index + 1) < datas.length) {
                    if (datas[index + 1]) {
                      dataline.push({
                        id: uuid('link'),
                        startId: id,
                        endId: datas[index + 1].stepId,
                        meta: '',
                        // startAt: [(index === 0 || item.workTypeId === '0') ? 90 : 120, (index === 0 || item.workTypeId === '0') ? 25 : 35],
                        // endAt: [0, (index === 0 || item.workTypeId === '0') ? 25 : 35]
                        startAt: [120, 35],
                        endAt: [0, 35]
                      })
                    }
                  }
                })
              })
              
              this.$nextTick(() => {
                setTimeout(() => {
                  this.nodeList = datanode
                  this.linkList = dataline
                }, 200)
              })
            }
          }
        })
      },
      linkDesc (link) {
        return link.meta ? link.meta.desc : ''
      },
      settingSubmit () {
        this.$refs['nodeSetting'].validate((valid) => {
          if (valid) {
            const conf = this.drawerConf
            if (this.drawerConf.type === drawerType.node) {
              if (!conf.info.meta) conf.info.meta = {}
              Object.keys(this.nodeSetting).forEach(key => {
                if (key == 'operatorIds') {
                  let idList = this.nodeSetting[key];
                  let nameList = [];
                  idList.forEach(id => {
                    let name = this.operatorList.find(item => {
                      return item.userId === id
                    }).name
                    nameList.push(name)
                  })
                 
                  this.$set(conf.info.meta, 'desc', nameList.join(','))
                }
                this.$set(conf.info.meta, key, this.nodeSetting[key])
              })
              this.$refs.nodeSetting.resetFields()
            } else {
              if (!conf.info.meta) conf.info.meta = {}
              Object.keys(this.linkSetting).forEach(key => {
                this.$set(conf.info.meta, key, this.linkSetting[key])
              })
              this.$refs.linkSetting.resetFields()
            }
            conf.visible = false
          }
        })
      },
      dataFormSubmit () {},
      getLineData (dataAll, dList, lList, id, sortNo) {
        const _l = []
        lList.forEach(l => {
          if (l.start.id === id) {
            _l.push(l.end.id)
          }
        })
        if (!sortNo) {
          const data = dList.filter(v => v.meta.prop === 'start')[0]
          _l.forEach(item => {
            dataAll.push([{
              'notes': data.meta.desc || '',
              'sortNo': 0,
              'stepId': data.id,
              'stepName': data.meta.name,
              'workTypeId': data.meta.workTypeId || null,
              'type': data.meta.type || null,
              'coordinate': data.coordinate.join(','),
              'operatorIds': data.meta.operatorIds
            }])
          })
        }
        dList.forEach(v => {
          const _i = _l.indexOf(v.id)
          if (_i > -1) {
            if (!v.meta.workTypeId && v.meta.prop !== 'end') {
              this.$message.error('完善节点工种')
              return
            }
            if (!sortNo) {
              dataAll[_i].push({
                'notes': v.meta.desc || '',
                'sortNo': (sortNo + 1),
                'stepId': v.id,
                'stepName': v.meta.name,
                'workTypeId': v.meta.workTypeId || null,
                'type': v.meta.type || null,
                'coordinate': v.coordinate.join(',')
              })
              this.getLineData(dataAll[_i], dList, lList, v.id, (sortNo + 1))
            } else {
              let _has = false
              dataAll.forEach(items => {
                if (items.stepId === v.id) {
                  _has = true
                }
              })
              if (!_has) {
                dataAll.push({
                  'notes': v.meta.desc || '',
                  'sortNo': (sortNo + 1),
                  'stepId': v.id,
                  'stepName': v.meta.name,
                  'workTypeId': v.meta.prop === 'end' ? 0 : (v.meta.workTypeId || ''),
                  'type': v.meta.type || '',
                  'coordinate': v.coordinate.join(',')
                })
              }
              this.getLineData(dataAll, dList, lList, v.id, (sortNo + 1))
            }
          }
        })
      }
    }
  }
</script>

<style scoped lang='scss'>
</style>
