<template>
  <div class="app-container">
    <div class="left">
      <!-- 岗位树 -->
      <div class="deptTree">
        <div class="head-container">
          <el-input
            v-model="queryParams.workstationName"
            placeholder="请在下方选择岗位名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @input="handleInputChange"
            @clear="handleClear"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="workstationOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="treeData"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
            highlight-current
          />

        </div>
      </div>
    </div>
    <div class="right">
      <el-radio-group v-model="tabPosition" style="margin-bottom: 30px">
        <el-radio-button label="craft">工艺</el-radio-button>
        <el-radio-button label="device">设备</el-radio-button>
      </el-radio-group>

      <div v-if="tabPosition === 'craft' || tabPosition === 'device'">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
        >
          <el-form-item :label="tabPosition === 'craft' ? '工艺名称' : '设备名称'" prop="machineryName">
            <el-input
              v-model="queryParams.machineryName"
              :placeholder="tabPosition === 'craft' ? '请输入工艺名称' : '请输入设备名称'"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              v-no-more-click
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索
            </el-button>
            <el-button
              v-no-more-click
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-no-more-click
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['iscs:machinery:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-no-more-click
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['iscs:machinery:remove']"
            >批量删除
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-if="refreshTable"
          v-loading="loading"
          :data="deptList"
          row-key="machineryId"
          :default-expand-all="isExpandAll"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column
            prop="machineryId"
            :label="tabPosition === 'craft' ? '工艺编号' : '设备编号'"
          ></el-table-column>
          <el-table-column
            prop="machineryName"
            :label="tabPosition === 'craft' ? '工艺名称' : '设备名称'"
          ></el-table-column>
          <el-table-column
            prop="workstationName"
            label="岗位"
          ></el-table-column>
          <el-table-column
            prop="machineryImg"
            :label="tabPosition === 'craft' ? '工艺图' : '设备图'"
          >
            <template slot-scope="scope">
              <div  class="img-box" >
                <el-image
                  style="width: 75px; height: 75px"
                  :preview-teleported="true"
                  class="images"
                  :hide-on-click-modal=true
                  :src="scope.row.machineryImg"
                  :zoom-rate="1.2"
                  :preview-src-list="[scope.row.machineryImg]"
                  :initial-index="1"
                  fit="cover" >
                </el-image>
                <i class="el-icon-zoom-in" id="eyeicon"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="详情"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-no-more-click
                size="mini"
                type="text"
                @click="handleLook(scope.row)"
              >查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-no-more-click
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['iscs:machinery:edit']"
              >修改
              </el-button>
              <el-button
                v-no-more-click
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['iscs:machinery:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total1 > 0&&tabPosition=='craft'"
          :total="total1"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
        <pagination
          v-show="total2 > 0&&tabPosition=='device'"
          :total="total2"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="460px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="上级" prop="parentId">-->
<!--          <treeselect-->
<!--            v-model="form.parentId"-->
<!--            :options="machineryOptions"-->
<!--            :normalizer="normalizer"-->
<!--            placeholder="选择上级"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item :label="this.tabPosition=='craft'?'工艺名称':'设备名称'" prop="machineryName">
          <el-input
            v-model="form.machineryName"
            placeholder="请输入名称"
          />
        </el-form-item>
<!--        <el-row>-->
<!--          <el-col :span="18">-->
<!--            <el-form-item :label="this.tabPosition=='craft'?'工艺编号':'设备编号'" prop="machineryCode">-->
<!--              <el-input-->
<!--                v-model="form.machineryCode"-->
<!--                placeholder="请输入编号"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label-width="30">-->
<!--              <el-switch-->
<!--                v-model="autoGenFlag"-->
<!--                active-color="#13ce66"-->
<!--                active-text="自动生成"-->
<!--                @change="handleAutoGenChange(autoGenFlag)"-->
<!--              >-->
<!--              </el-switch>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        mars岗位-->
        <el-form-item label="岗位" prop="workstationId" >
          <treeselect
            v-model="form.workstationId"
            :options="marsOptions"
            :normalizer="Marsnormalizer"
            placeholder="请选择岗位"
          />
        </el-form-item>
        <el-form-item label="所属电柜" prop="lotoId">
          <el-select
            style="width: 300px"
            v-model="form.lotoId"
            placeholder="请选择所属电柜"
          >
            <el-option
              v-for="dict in LotoOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="设备/工艺类型" prop="machineryType">-->
<!--          <el-input-->
<!--            v-model="form.machineryType"-->
<!--            placeholder="请输入设备/工艺类型"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item :label="this.tabPosition=='craft'?'工艺图':'设备图'" prop="machineryImg">
          <ImageUploadSingle
            :limit="1"
            :value="form.machineryImg"
            :fileSize="5"
            @onUploaded="handleIconUplaoded"
            @onRemoved="handleIconRemoved"
          ></ImageUploadSingle>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm"
        >确 定
        </el-button
        >
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  listTechnology,
  addTechnology,
  updateTechnology,
  delTechnology,
  getTechnologyInfo
} from '@/api/system/machinery'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { genCode } from '@/api/system/autocode/rule'
import { listMarsDept } from '@/api/system/marsdept'
import { listLoto } from '@/api/mes/lotoStation/lotoStation'

export default {
  name: 'Dept',
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      //自动生成编码
      autoGenFlag: false,
      isEditing: false, // 增加一个标识变量
      tabPosition: 'craft',
      total1:0,//工艺分页
      total2:0,//设备分页
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // mars树选项
      marsOptions: [],
      //工艺树
      machineryOptions: [],
      // 电柜
      lotoOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        machineryName: undefined,
        machineryCode: undefined,
        machineryType: undefined,
        workstationName:undefined,
        workstationId:undefined,
      },

      LotoOptions: [], //电柜绑定
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        machineryCode: [
          { required: true, message: '设备/工艺编码不能为空', trigger: 'blur' }
        ],
        machineryName: [
          { required: true, message: '设备/工艺名称不能为空', trigger: 'blur' }
        ],
        workstationId: [
          { required: true, message: '岗位不能为空', trigger: 'blur' }
        ],
        lotoId: [{ required: true, message: '电柜不能为空', trigger: 'blur' }]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      workstationOptions: []//岗位
    }
  },
  created() {
    this.getList()
    this.getOtherList()
  },
  watch: {
    'form.workstationId': function(newVal, oldVal) {
      if(newVal!==oldVal&&this.form.lotoId&&!this.isEditing) {
        this.form.lotoId = ''
      }
      if (newVal) {
        const data = {
          pasge: 1,
          size: -1,
          workstationId: this.form.workstationId
        }
        listLoto(data).then((response) => {
          this.LotoOptions = response.data.records.map((item) => {
            return {
              value: item.lotoId,
              label: item.lotoName
            }
          })
        })
      }
    },
    "tabPosition":function(newVal, oldVal){
      if(newVal){
        this.getList()
      }
    }
  },

  methods: {

    /** 查询部门列表 */
    getList() {
      this.loading = true
      if (this.tabPosition == 'craft') {
        this.queryParams.machineryType='工艺'
        listTechnology(this.queryParams).then((response) => {
          this.deptList=response.data.records
          this.total1=response.data.total;
          // 设备新增的下拉
          this.machineryOptions = this.handleTree(
            response.data.records,
            'machineryId',
            'parentId'
          )

          this.loading = false
        })
      } else {
        this.queryParams.machineryType='设备'
        listTechnology(this.queryParams).then((response) => {
          this.deptList=response.data.records
          this.total2=response.data.total;
          // 设备新增的下拉
          this.machineryOptions = this.handleTree(
            response.data.records,
            'machineryId',
            'parentId'
          )

          this.loading = false
        })

      }

    },
    getOtherList(){
      const data = {
        pasge: 1,
        size: -1
      }

      listLoto(data).then((response) => {
        this.LotoOptions = response.data.records.map((item) => {
          return {
            value: item.lotoId,
            label: item.lotoName
          }
        })
      })

      listMarsDept(data).then((response) => {
        // 新增岗位单选
        this.marsOptions = this.handleTree(
          response.data.records,
          'workstationId',
          'parentId'
        )
        // mars岗位树数据
        this.workstationOptions = this.transformToTree(response.data.records)
        // 使用递归函数查找匹配的节点
        const selectedTreeNode = this.findNodeById(this.workstationOptions, this.queryParams.workstationId)
        // 调用 handleNodeClick 方法
        if (selectedTreeNode) {
          this.handleNodeClick(selectedTreeNode)
        } else {
          console.log('未找到匹配的节点')
        }

      })
    },
    // 过滤设备工艺children数据类型是
    filterByMachineryType(records, machineryType) {
      return records.reduce((acc, item) => {
        if (item.machineryType === machineryType) {
          // 过滤符合条件的父级
          const filteredItem = { ...item };

          // 如果有子级，则递归过滤子级
          if (item.children && item.children.length > 0) {
            filteredItem.children = this.filterByMachineryType(item.children, machineryType);
          }

          // 将符合条件的父级和子级添加到结果中
          acc.push(filteredItem);
        } else if (item.children && item.children.length > 0) {
          // 父级不符合条件，但子级可能符合条件，递归过滤子级
          const filteredChildren = this.filterByMachineryType(item.children, machineryType);
          if (filteredChildren.length > 0) {
            acc.push({ ...item, children: filteredChildren });
          }
        }
        return acc;
      }, []);
    },

    // mars岗位数深层次遍历
    findNodeById(nodes, targetId) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.id === targetId) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findNodeById(node.children, targetId)
          if (foundNode) {
            return foundNode
          }
        }
      }
      return null
    },
    /** 转换mars岗位树数据为树形结构 */
    transformToTree(records) {
      const recordMap = {} // 创建一个 Map 以存储所有记录
      const tree = [] // 最终返回的树形结构

      // 初始化所有记录到 Map
      records.forEach(record => {
        recordMap[record.workstationId] = {
          id: record.workstationId,
          label: record.workstationName,
          children: []
        }
      })

      // 遍历记录并构建树
      records.forEach(record => {
        const parentId = record.parentId

        if (parentId === '0') {
          // 如果是顶层节点，直接添加到树中
          tree.push(recordMap[record.workstationId])
        } else if (recordMap[parentId]) {
          // 如果有父节点，则将当前节点加入父节点的 children 中
          recordMap[parentId].children.push(recordMap[record.workstationId])
        }
      })

      return tree
    },
    // mars岗位树点击事件
    handleNodeClick(data) {
      this.queryParams.workstationId = data.id;//这里给查询传递参数
      this.queryParams.workstationName = data.label;//这里给回显框显示中文
      const data1 = {
        pasge: 1,
        size: -1
      }
      listMarsDept(data1).then((response) => {
        // 新增岗位单选
        this.marsOptions = this.handleTree(
          response.data.records,
          'workstationId',
          'parentId'
        )
        // mars岗位树数据
        this.workstationOptions = this.transformToTree(response.data.records)
        // 使用递归函数查找匹配的节点
        const selectedTreeNode = this.findNodeById(this.workstationOptions, this.queryParams.workstationId)
        // 不再递归调用 handleNodeClick
        if (selectedTreeNode) {
          // 可以在这里执行其他逻辑，但不要再次调用 handleNodeClick
          console.log('找到匹配的节点:', selectedTreeNode)
        } else {
          console.log('未找到匹配的节点')
        }
      });
      listTechnology(this.queryParams).then((response) => {
        debugger;
        let filteredData;
        if (this.tabPosition == 'craft') {
          filteredData = this.filterByMachineryType(response.data.records, '工艺');
          console.log(filteredData, '工艺列表---a');
        } else {
          filteredData = this.filterByMachineryType(response.data.records, '设备');
          console.log(filteredData, '设备列表---v');
        }

        this.deptList = this.handleTree(
          filteredData,
          'machineryId',
          'parentId'
        );


        // 岗位新增的下拉
        this.machineryOptions = this.handleTree(
          response.data.records,
          'machineryId',
          'parentId'
        )
        this.loading = false
      })
    },
    /** 转换mars岗位数据结构 */
    Marsnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.workstationId,
        label: node.workstationName,
        children: node.children
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // mars树形输入框回显监听
    handleInputChange() {
      this.$refs.treeData.filter(this.queryParams.workstationId) // 调用树的 filter 方法
      const data={
        page:1,
        size:-1,
        workstationId:null,
        workstationName:null
      }
      listMarsDept(data).then((response) => {
        // 新增岗位单选
        this.marsOptions = this.handleTree(
          response.data.records,
          'workstationId',
          'parentId'
        )
        // mars岗位树数据
        this.workstationOptions = this.transformToTree(response.data.records)
        // 使用递归函数查找匹配的节点
        // const selectedTreeNode = this.findNodeById(this.workstationOptions, this.queryParams.workstationId)
        // 不再递归调用 handleNodeClick
        // if (selectedTreeNode) {
        //   // 可以在这里执行其他逻辑，但不要再次调用 handleNodeClick
        //   console.log('找到匹配的节点:', selectedTreeNode)
        // } else {
        //   console.log('未找到匹配的节点')
        //
        // }
      })

    },
    // 岗位查询 清除事件
    handleClear(){
      this.queryParams.workstationId = ''
      this.queryParams.workstationName=''
      this.getList()
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.machineryId,
        label: node.machineryName,
        children: node.children
      }
    },

    // 地图预览
    look(row) {
      console.log(row, 'row预览')
      const data = row.lotoId
      this.$router.push(
        `/mes/dv/technology/technologyList/index/MapData?lotoId=${data}&machineryId=${row.machineryId}`
      )
      // this.dialogVisibleMap = true; // 显示地图预览弹框
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        machineryId: undefined,
        parentId: undefined,
        machineryName: undefined,
        workstationId: undefined,
        workstationName: undefined,
      }
      this.autoGenFlag = false
      this.resetForm('form')
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('TECHNOLOGY_CODE').then((response) => {
          console.log(response, '设备工艺编码')
          this.form.machineryCode = response
        })
      } else {
        this.form.machineryCode = null
      }
    },
    //图标上传成功
    handleIconUplaoded(imgUrl) {
      this.form.machineryImg = imgUrl[0].url
    },
    // 图标移除
    handleIconRemoved(imgUrl) {
      this.form.machineryImg = null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.workstationName = undefined;
      this.queryParams.workstationId = undefined;
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != null && row.machineryId) {
        this.form.parentId = row.machineryId
      } else {
        this.form.parentId = null
      }

      // 在工艺新增就是工艺 设备新增就是设备
      if(this.tabPosition=='craft'){
        this.form.machineryType='工艺'
        this.title = '新增工艺'
      }else if(this.tabPosition=='device'){
        this.form.machineryType='设备'
        this.title = '新增设备'
      }
      this.open = true

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.isEditing = true
      getTechnologyInfo(row.machineryId).then((response) => {
        this.form = response.data
        this.open = true
        if(this.tabPosition=='craft'){
          this.form.machineryType='工艺'
          this.title = '修改工艺'
        }else if(this.tabPosition=='device'){
          this.form.machineryType='设备'
          this.title = '修改设备'
        }
        setTimeout(()=>{
          this.isEditing = false
        },1000)
      })
    },
    handleLook(row) {
      // 工艺详情
      if (this.tabPosition == "craft") {
        this.$router.push("/mes/dv/technology/technologyDetail/CraftDetail?machineryId=" + row.machineryId);
      } else {
        // 设备详情
        this.$router.push("/mes/dv/technology/technologyDetail/DeviceDetail?machineryId=" + row.machineryId);
      }
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.machineryId != undefined) {
            updateTechnology(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            if(this.form.parentId==null){
              this.form.parentId=0
            }
            addTechnology(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.machineryId)
      this.codes = selection.map((item) => item.machineryCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const machineryIds = row.machineryId || this.ids;
      this.$modal.confirm('确认是否删除所选数据项？').then(function() {
        return delTechnology(machineryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
}
</script>
<style scoped lang="scss">

.img-box {
  width: 75px;
  height: 75px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box:hover {
  background: #000;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 40%;
    z-index:100;
    color: white;
    pointer-events:none
  }
}

.app-container {
  width: 100%;
  height: 100%;
  display: flex;
}

.left {
  width: 15%;
  height: 100%;
  margin-right: 10px;
  /* background: green; */
}

.deptTree {
  width: 100%;
  height: 90%;
  /* background: pink; */
}

.right {
  width: 83%;
  height: 100%;
  /* background: yellow; */
}
</style>
