<template>
  <div class="app-container">
    <el-radio-group v-model="tabPosition" style="margin-bottom: 30px">
      <el-radio-button label="craftInfo">工艺信息</el-radio-button>
      <el-radio-button label="deviceList">设备列表</el-radio-button>
      <el-radio-button label="Loto">锁定站</el-radio-button>
      <el-radio-button label="sopList">SOP列表</el-radio-button>
    </el-radio-group>
<!--    工艺信息-->
    <div class="craft" v-if="this.tabPosition == 'craftInfo'">
      <Tinymce  />
<!--      富文本编辑器-->
    </div>
    <!-- 设备列表 -->
    <div class="device" v-if="this.tabPosition == 'deviceList'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-if="this.tabPosition == 'deviceList'"
            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>
        <!-- <el-col :span="1.5">
          <el-button
            v-no-more-click
            type="info"
            plain
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
            >展开/折叠
          </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="machineryCode"
          label="设备编码"
        ></el-table-column>
        <el-table-column
          prop="machineryName"
          label="设备名称"
        ></el-table-column>
        <el-table-column
          prop="machineryImg"
          label="设备图"
        >
          <template slot-scope="scope">
            <img :src="scope.row.machineryImg" alt="" style="width: 50px; height: 50px;"/>
          </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>
    </div>
    <!-- LOTO站 -->
    <div class="loto">
      <MapData v-if="tabPosition=='Loto'" :machineryId="this.$route.query.machineryId"></MapData>
    </div>
    <!-- SOP列表 -->
    <div class="sopList" v-if="this.tabPosition == 'sopList'">
      <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="handleAddSopList"
            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="handleSopDelete"
            v-hasPermi="['iscs:machinery:remove']"
          >批量删除
          </el-button
          >
        </el-col>
      </el-row>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="SopList"
        row-key="machineryId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionSopChange"
      >
        <el-table-column type="selection" width="55" align="center"/>

        <el-table-column
          prop="sopName"
          label="sop名称"
        ></el-table-column>
        <el-table-column
          prop="machineryName"
          label="工作内容"
        ></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="handleSopUpdate(scope.row)"
              v-hasPermi="['iscs:machinery:edit']"
            >编辑
            </el-button>
            <!-- <el-button
                v-no-more-click
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['iscs:machinery:add']"
                >新增
              </el-button> -->
            <!--          v-if="scope.row.parentId != 0"-->
            <el-button
              v-no-more-click
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleSopDelete(scope.row)"
              v-hasPermi="['iscs:machinery:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <pagination
      v-show="total1 > 0&&tabPosition=='deviceList'"
      :total="total1"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <pagination
      v-show="total2 > 0&&tabPosition=='sopList'"
      :total="total2"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加或修改设备列表对话框 -->
    <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="设备名称" prop="machineryName">
          <el-input
            v-model="form.machineryName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-row>
          <el-col :span="17">
            <el-form-item label="设备编号" prop="machineryCode">
              <el-input
                v-model="form.machineryCode"
                placeholder="请输入设备编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <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="formMarsOptions"
            :normalizer="Marsnormalizer"
            placeholder="请选择岗位"
            disabled
          />
        </el-form-item>
        <el-form-item label="所属电柜" prop="lotoId">
          <el-select
            style="width: 300px"
            v-model="form.lotoId"
            placeholder="请选择所属电柜"
            disabled
          >
            <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="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>
    <!-- 添加或修改sopLise对话框 -->
    <el-dialog :title="titlesop" :visible.sync="openSop" width="470px" append-to-body>
      <el-form ref="sopform" :model="sopform" :rules="rules" label-width="100px">
        <el-form-item label="所属岗位" prop="workstationId" >
          <treeselect v-model="sopform.workstationId" :options="marsOptions"  :normalizer="Marsnormalizer" placeholder="选择岗位" disabled/>
        </el-form-item>
        <el-form-item label="设备/工艺" prop="machineryId" >
          <treeselect v-model="sopform.machineryId" :options="machineryOptions"  :normalizer="normalizer" placeholder="选择设备/工艺" disabled/>
        </el-form-item>
        <el-form-item label="SOP类型" prop="sopType">
          <el-select v-model="sopform.sopType"  placeholder="请选择SOP类型" clearable>
            <el-option
              v-for="dict in dict.type.sop_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitSopForm">确 定</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'
import MapData from '@/views/mes/dv/technology/technologyDetail/MapData.vue'
import {
  addinsertIsMarsSop,
  deleteIsMarsSopByMarsSopIds,
  getIsMarsSopPage, selectIsMarsSopById,
  updateIsMarsSop
} from '@/api/mes/sop/sopindex'
import Tinymce from '@/components/tinymce/example/Index.vue'
import { delMachinery } from '@/api/mes/dv/machinery'
export default {
  name: 'Dept',
  dicts: ['sys_normal_disable','sop_type'],
  components: { Treeselect, MapData,Tinymce },
  data() {
    return {
      // 遮罩层
      loading: true,
      //自动生成编码
      autoGenFlag: false,
      tabPosition: 'craftInfo',
      total1:0,//设备列表
      total2:0,//sop列表
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // mars树选项
      marsOptions: [],
      // 新增设备时 岗位树结构
      formMarsOptions:[],
      //工艺树
      machineryOptions: [],
      // 电柜
      lotoOptions: [],
      // 弹出层标题
      title: '',
      titlesop:'',
      // 是否显示弹出层
      open: false,
      openSop:false,//新增sop列表
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        machineryName: undefined,
        machineryCode: undefined,
        machineryId: undefined,
      },
      LotoOptions: [], //电柜绑定
      // 表单参数
      form: {

      },
      sopform:{

      },
      ids:null,//设备列表多选
      sopids:null,//sop列表多选
      SopList: [],//sopLisT
      queryParamsSop: {
        current: 1,
        size: 10,
        machineryId: undefined,
        machineryType:undefined,
      },
      machineryId:null,//
      // 表单校验
      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' }]
      }
    }
  },

  watch: {

    // 监听 tabPosition 的变化
    tabPosition(newVal) {
      if (newVal === 'craftInformation') {
        // 当 tabPosition 为 "craftInformation" 时跳转
        this.$router.push('/technology/technologyList')
      }
    }
  },
  created() {
    this.getList()
    this.getOtherList()
    this.getTechnologyAllData()

    this.form.machineryId = this.$route.query.machineryId
    this.machineryId = this.$route.query.machineryId
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true
        const data={
        ...this.queryParams,
          parentId: this.$route.query.machineryId,
          machineryType:'设备'
        }
      listTechnology(data).then((response) => {
        debugger;
        const filterData = response.data.records
        this.total1=response.data.total
        this.deptList = filterData
        this.loading = false
      })

    },

    // 获取sop新增选设备工艺的回显数据
    getTechnologyAllData(){
      const data={
        current: 1,
        size: -1,
      }
      listTechnology(data).then((response) => {
        this.machineryOptions = response.data.records
        this.loading = false
      })
      const data1 = {
        pasge: 1,
        size: -1
      }
      listMarsDept(data1).then((response) => {
        this.marsOptions = response.data.records
        // 下面数据是给新增设备的时候回显数据
        this.formMarsOptions = this.handleTree(response.data.records,"workstationId","parentId")
      })
      listLoto(data1).then((response) => {
        this.LotoOptions = response.data.records.map((item) => {
          return {
            value: item.lotoId,
            label: item.lotoName
          }
        })
      });

    },
    getOtherList(){
      this.queryParamsSop.machineryId=this.$route.query.machineryId
      getIsMarsSopPage(this.queryParamsSop).then(response => {
        debugger;
        this.SopList = response.data.records
        this.total2=response.data.total
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    Marsnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.workstationId,
        label: node.workstationName,
        children: node.children
      }
    },
    /** 转换mars岗位数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.machineryId,
        label: node.machineryName,
        children: node.children
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.openSop=false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        machineryId: undefined,
        parentId: undefined,
        machineryName: undefined,
        machineryCode: undefined,
      }
      this.autoGenFlag = false
      this.resetForm('form')
      this.resetForm('sopform')
    },
    //自动生成编码
    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.resetForm('queryForm')
      this.handleQuery()
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    callback(openType) {
      getTechnologyInfo(this.$route.query.machineryId).then((response) => {
        console.log(response, '工艺新增sop');
        this.sopform.workstationId = response.data.workstationId;
        this.sopform.machineryId = response.data.machineryId;
        this.form.workstationId = response.data.workstationId;
        this.form.lotoId = response.data.lotoId;
        this.form.machineryType = '设备';
        console.log(this.form, '工艺新增sop-id--设备的回显');

        // 根据 openType 打开不同的弹窗
        if (openType === 'device') {
          this.open = true;
          this.title = '添加设备';
        } else if (openType === 'sop') {
          this.openSop = true;
          this.titlesop = '添加SOP';
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.parentId = this.$route.query.machineryId;
      this.callback('device');
    },
    /** 新增sop按钮操作 */
    handleAddSopList() {
      this.reset();
      this.callback('sop');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form.machineryType='设备'
      getTechnologyInfo(row.machineryId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改设备'
      })
    },
    handleSopUpdate(row) {
      this.reset()
      selectIsMarsSopById(row.sopId).then(response => {
        this.sopform = response.data
        this.openSop = true
        this.titlesop = '修改SOP'
      })
    },
    /** 提交按钮 */
    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 {
            addTechnology(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // sop新增
    submitSopForm: function() {
      this.$refs['sopform'].validate((valid) => {
        if (valid) {
          if (this.sopform.sopId != undefined) {
            updateIsMarsSop(this.sopform).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.openSop = false
              this.getOtherList()
            })
          } else {
            addinsertIsMarsSop(this.sopform).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.openSop = false
              this.getOtherList()
            })
          }
        }
      })
    },
    // 多选框选中数据
    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
    },
    // sop列表多选
    handleSelectionSopChange(selection) {
      this.sopids = selection.map((item) => item.sopId)
      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(() => {});

    },
    handleSopDelete(row){
      const sopIds = row.sopId || this.sopids;
      this.$modal.confirm('确认删除数据项？').then(function() {
        return deleteIsMarsSopByMarsSopIds(sopIds);
      }).then(() => {
        this.getOtherList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
}
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 100%;
}

.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>
