<template>
  <div class="app-container" v-loading="fileAnalysisLoading" :element-loading-text="'设计文件解析中...'">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="单元名称" prop="deptName">
        <el-input
            v-model="queryParams.deptName"
            placeholder="请输入单元名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button 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
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:dept:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            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="consUnitInfoList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="施工单元名称" width="200" prop="name"/>
      <el-table-column label="强夯类型" prop="penningType"/>
      <el-table-column label="类型" prop="type"/>
      <el-table-column label="设计文件类型" prop="classifyType"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(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-if="scope.row.type==='2'"
              size="mini"
              type="text"
              icon="el-icon-upload"
              @click="handleImport(scope.row)"
              v-hasPermi="['system:dept:edit']"
          >
            上传设计文件
          </el-button>
          <el-button
              v-if="scope.row.type==='2'"
              size="mini"
              type="text"
              icon="el-icon-set-up"
              @click="handleAssign(scope.row)"
              v-hasPermi="['system:dept:edit']"
          >
            分配施工机械
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']"
          >新增
          </el-button>
          <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dept:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级施工单元" prop="parentId">
              <treeselect v-model="form.parentId" :options="consUnitOptions" :normalizer="normalizer"
                          placeholder="选择上级施工单元"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="施工单元名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入施工单元名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建类型" prop="createType">
              <el-input v-model="form.createType" placeholder="请输入创建类型"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="强夯类型" prop="penningType">
              <el-input v-model="form.penningType" placeholder="请输入强夯类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择节点类型">
                <el-option
                    v-for="dict in dict.type.cons_unit_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设计文件类型" prop="classifyType">
              <el-input v-model="form.classifyType" placeholder="请输入设计文件类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="施工桩机" prop="toMachineId">
              <el-select style="width: 100%" v-model="form.machineId" multiple placeholder="请选择桩机">
                <el-option
                    v-for="machine in machineList"
                    :key="machine.id"
                    :label="`${machine.machineNum}(${machine.equipment})`"
                    :value="machine.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @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"
          name="files"
          accept=".dwg,.xls,.xlsx"
          :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">{{ $t("common.importModeMsg") }}</div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            {{ $t("common.importMessage") }}
          </div>
          <span>{{ $t("common.importFileType", {fileType: 'DWG'}) }}</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配施工机械" :visible.sync="assignDialog.open" width="700px" append-to-body>
      <el-form ref="assignform" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="施工单元">
              {{ form.name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="施工桩机" prop="toMachineId">
              <el-select style="width: 100%" v-model="form.machineId" multiple placeholder="请选择桩机">
                <el-option
                    v-for="machine in machineList"
                    :key="machine.id"
                    :label="`${machine.machineNum}(${machine.name})`"
                    :value="machine.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignForm">确 定</el-button>
        <el-button @click="assignDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  addConsUnitInfo,
  assignMachine,
  delConsUnitInfo,
  getConsUnitInfo,
  importCad,
  listAllConsUnitExcludeChild,
  listConsUnitInfo,
  updateConsUnitInfo
} from "@/api/cons/consUnitInfo";
import {listAllPileMachineInfo} from "@/api/cons/pileMachineInfo";
import {getToken} from "@/utils/auth";

export default {
  name: "cons-unit",
  dicts: ['cons_unit_type'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      fileAnalysisLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 施工单元表格数据
      consUnitInfoList: [],
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      machineList: [],
      consUnitOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: undefined
      },
      importConsUnit: {},
      // 表单参数
      form: {
        type: "0",
        createType: 1,
        classifyType: "excel",
      },
      upload: {
        title: this.$t("cons.pileHoleImportTitle"),
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploads"
      },
      assignDialog: {
        open: false
      },
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级部门不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "施工单元名称不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getMachineList();
  },
  methods: {
    handleAssign(record) {
      this.reset();
      getConsUnitInfo(record.id).then(response => {
        this.form = response.data;
        this.assignDialog.open = true;
      });
    },
    submitAssignForm() {
      this.$refs["assignform"].validate(valid => {
        if (valid) {
          assignMachine(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.assignDialog.open = false;
            this.getList();
          });
        }
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleImport(record) {
      this.upload.open = true;
      this.importConsUnit = record
    },
    // 文件上传中处理
    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.fileAnalysisLoading = true;
      importCad({
        fileId: response.fileNames,
        id: this.importConsUnit.id,
      }).finally(() => {
        this.fileAnalysisLoading = false
      })
    },
    getMachineList() {
      this.loading = true;
      listAllPileMachineInfo({}).then(response => {
        this.machineList = response.rows
      });
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listConsUnitInfo(this.queryParams).then(response => {
        this.consUnitInfoList = this.handleTree(response.rows, "id");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        penningType: null,
        type: "0",
        parentId: null,
        createType: 1,
        classifyType: "excel",
        name: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加施工单元";
      listConsUnitInfo().then(response => {
        this.consUnitOptions = this.handleTree(response.rows, "id");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getConsUnitInfo(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改施工单元";
        listAllConsUnitExcludeChild(row.id).then(response => {
          this.consUnitOptions = this.handleTree(response.data, "id");
          if (this.consUnitOptions.length == 0) {
            const noResultsOptions = {id: this.form.parentId, name: this.form.parentName, children: []};
            this.consUnitOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateConsUnitInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConsUnitInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function () {
        return delConsUnitInfo(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
