<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <!--      <el-form-item label="SOP编号" prop="sopCode">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.sopCode"-->
      <!--          placeholder="请输入SOP编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="SOP名称" prop="sopName">
        <el-input
          v-model="queryParams.sopName"
          placeholder="请输入sop名称"
          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:mars:sop:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iscs:sop:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['iscs:sop:import']"
          >导入</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" empty-text="暂无数据">
      <!--      <el-table-column prop="sopIndex" label="SOP序号" ></el-table-column>-->
      <el-table-column
        prop="sopName"
        label="SOP名称"
        width="360"
      ></el-table-column>
      <el-table-column prop="sopType" label="SOP类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sop_type" :value="scope.row.sopType" />
        </template>
      </el-table-column>
      <el-table-column prop="workstationName" label="所属岗位">
        <template slot-scope="scope">
          <span>{{ scope.row.workstationName }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="machineryName" label="设备/工艺">
        <template slot-scope="scope">
          {{ scope.row.machineryName }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </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:mars:sop:edit', 'iscs:mars:sop:query']"
            >修改
          </el-button>

          <!--          v-if="scope.row.parentId != 0"-->
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:mars:sop:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="470px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!--        <el-form-item label="权重序号" prop="sopIndex">-->
        <!--          <el-input v-model="form.sopIndex" placeholder="请输入权重序号"/>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="SOP名称" prop="sopName">-->
        <!--          <el-input v-model="form.sopName" placeholder="请输入SOP名称"/>-->
        <!--        </el-form-item>-->
        <!--        <el-row>-->
        <!--          <el-col :span="18">-->
        <!--            <el-form-item label="SOP编号" prop="sopCode">-->
        <!--              <el-input-->
        <!--                v-model="form.sopCode"-->
        <!--                placeholder="请输入SOP编号"-->
        <!--              />-->
        <!--            </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>-->
        <el-form-item label="SOP类型" prop="sopType">
          <el-select
            v-model="form.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-item label="所属岗位" prop="workstationId">
          <treeselect
            v-model="form.workstationId"
            :options="marsOptions"
            :normalizer="Marsnormalizer"
            placeholder="选择岗位"
            @change="handleWorkstationChange"
          />
        </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="machineryId">
          <treeselect
            v-model="form.machineryId"
            :options="machineryOptions"
            :normalizer="machinerynormalizer"
            placeholder="选择设备/工艺"
          />
        </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>
    <!--    导入文件-->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button v-no-more-click @click="upload.open = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getIsMarsSopPage,
  addinsertIsMarsSop,
  updateIsMarsSop,
  deleteIsMarsSopByMarsSopIds,
  selectIsMarsSopById,
  updateIsMarsSopIndexAPI,
} from "@/api/mes/sop/sopindex";
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 { listTechnology } from "@/api/system/machinery";
import Template from "@/views/print/printtemplate/list.vue";
import { getToken } from "@/utils/auth";

export default {
  name: "Dept",
  dicts: ["sys_normal_disable", "sop_type"],
  components: { Template, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      //自动生成编码
      autoGenFlag: false,
      // 显示搜索条件
      showSearch: true,
      isEditing: false, //添加一个标识符
      // 总条数
      total: 0,
      // 表格树数据
      deptList: [],
      // mars树选项
      marsOptions: [],
      //工艺树
      sopOptions: [],
      // 电柜
      lotoOptions: [],
      // 设备/工艺
      machineryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        sopName: undefined,
        sopCode: undefined,
      },
      LotoOptions: [], //电柜绑定
      // 表单参数
      form: {
        machineryId: "",
      },
      // 表单校验
      rules: {
        sopCode: [
          { required: true, message: "SOP编码不能为空", trigger: "blur" },
        ],
        sopName: [
          { required: true, message: "SOP名称不能为空", trigger: "blur" },
        ],
        workstationId: [
          { required: true, message: "岗位不能为空", trigger: "blur" },
        ],
        lotoId: [
          { required: true, message: "锁定站不能为空", trigger: "blur" },
        ],
        machineryId: [
          { required: true, message: "设备/工艺不能为空", trigger: "blur" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/iscs/mars/sop/importSop",
      },
    };
  },
  created() {
    this.getList();
    this.getOtherList();
  },
  watch: {
    "form.workstationId": function (newVal, oldVal) {
      if (newVal !== oldVal && this.form.machineryId && !this.isEditing) {
        this.form.machineryId = null;
      }
      if (newVal) {
        const data = {
          pasge: 1,
          size: -1,
          workstationId: this.form.workstationId,
        };

        listTechnology(data).then((response) => {
          const data = response.data.records.filter(
            (item) => item.machineryType == "工艺"
          );
          this.machineryOptions = this.handleTree(
            data,
            "machineryId",
            "parentId"
          );
        });
      }
    },
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      getIsMarsSopPage(this.queryParams).then((response) => {
        debugger;
        this.deptList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getOtherList() {
      const data = {
        pasge: 1,
        size: -1,
      };
      listMarsDept(data).then((response) => {
        this.marsOptions = this.handleTree(
          response.data.records,
          "workstationId",
          "parentId"
        );
      });
      listLoto(data).then((response) => {
        this.LotoOptions = response.data.records.map((item) => {
          return {
            value: item.lotoId,
            label: item.lotoName,
          };
        });
      });
      listTechnology(data).then((response) => {
        console.log(response, "涉笔啊哈就开始卡机");
        const data = response.data.records.filter(
          (item) => item.machineryType == "工艺"
        );
        console.log(data, "过滤之后");
        this.machineryOptions = this.handleTree(
          data,
          "machineryId",
          "parentId"
        );
      });
    },
    /** 转换mars岗位数据结构 */
    Marsnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.workstationId,
        label: node.workstationName,
        children: node.children,
      };
    },
    /** 转换mars岗位数据结构 */
    machinerynormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.machineryId,
        label: node.machineryName,
        children: node.children,
      };
    },
    handleWorkstationChange(value) {
      // 清空 machineryId
      this.form.machineryId = null;
      // 你可以在这里添加其他逻辑，比如根据 workstationId 加载 machineryOptions
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sopId: undefined,
        parentId: undefined,
        sopName: undefined,
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("SOP_CODE").then((response) => {
          console.log(response, "设备工艺编码");
          this.form.sopCode = response;
        });
      } else {
        this.form.sopCode = null;
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.sopName = "";
      this.handleQuery();
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "新增SOP";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEditing = true;
      selectIsMarsSopById(row.sopId).then((response) => {
        this.form = response.data;
        this.open = true;
        setTimeout(() => {
          this.isEditing = false;
        }, 1000);
        this.title = "修改SOP";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.sopId != undefined) {
            updateIsMarsSop(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;

              this.getList();
            });
          } else {
            addinsertIsMarsSop(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    // confirm('是否确认删除名称为"' + row.sopName + '"的数据项？')
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除所选数据项？")
        .then(function () {
          return deleteIsMarsSopByMarsSopIds(row.sopId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "iscs/mars/sop/exportIsMarsSop",
        {
          ...this.queryParams,
        },
        `sop_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "sop导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "iscs/mars/sop/importTemplate",
        {},
        `sop_item_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
