<template>
  <div class="app-container" v-loading="fileAnalysisLoading" :element-loading-text="$t('cons.cadAnalysis')">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('cons.unitName')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('common.typeInfo',{
            name: $t('cons.unitName')
          })"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
            $t('common.search')
          }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</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="['cons:consUnitInfo:add']"
        >
          {{ $t('common.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >
          {{ $t('common.expand_collapse') }}
        </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="$t('cons.unitName')" width="200" prop="name"/>
      <el-table-column :label="$t('cons.nodeType')" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cons_unit_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('cons.designFileType')" prop="classifyType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.classify_type" :value="scope.row.classifyType"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.updateTime')" align="center" prop="updateTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.createTime')" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cons:consUnitInfo:edit']"
          >
            {{
              $t('common.edit')
            }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['cons:consUnitInfo:add']"
          >
            {{
              $t('common.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="['cons:consUnitInfo:remove']"
          >
            {{
              $t('common.delete')
            }}
          </el-button>
          <br/>
          <el-button
            v-if="scope.row.type==='2'"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleImport(scope.row)"
            v-hasPermi="['cons:consUnitInfo:edit']"
          >
            {{
              $t('cons.uploadCAD')
            }}
          </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="['cons:consUnitInfo:edit']"
          >
            {{
              $t('cons.assignMachine')
            }}
          </el-button>
          <el-button
            v-if="scope.row.type==='2'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExport(scope.row)"
          >
            {{
              $t('cons.downloadFinishDrawing')
            }}
          </el-button>
          <el-button
            v-if="scope.row.type==='2'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExportCsv(scope.row)"
          >
            {{
              $t('cons.downloadPileData')
            }}
          </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="$t('cons.parentUnit')" prop="parentId">
              <treeselect v-model="form.parentId" :options="consUnitOptions" :normalizer="normalizer"
                          :placeholder="$t('common.select',{
                            name: $t('cons.parentUnit')
                          })"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('cons.unitName')" prop="name">
              <el-input
                v-model="form.name"
                :placeholder="$t('common.typeInfo',{
                            name: $t('cons.unitName')
                          })"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('cons.createType')" prop="createType">
              <el-input v-model="form.createType" :placeholder="$t('common.typeInfo',{
                            name: $t('cons.createType')
                          })"/>
            </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="$t('cons.nodeType')" prop="type">
              <el-select
                v-model="form.type"
                :placeholder="$t('common.select',{
                            name: $t('cons.nodeType')
                          })">
                <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-col :span="12" v-if="form.type == NodeType.desFile.code">
            <el-form-item :label="$t('cons.designFileType')" prop="classifyType">
              <el-select
                v-model="form.classifyType"
                :placeholder="$t('common.select',{
                            name: $t('cons.designFileType')
                          })"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.classify_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="24" v-if="form.type == NodeType.desFile.code">
            <el-form-item :label="$t('cons.machine')" prop="toMachineId">
              <el-select style="width: 100%" v-model="form.machineId" multiple
                         :placeholder="$t('common.select',{name:$t('cons.machine')})">
                <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="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.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">{{ $t('common.confirm') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t('cons.assignMachine')" :visible.sync="assignDialog.open" width="500px" append-to-body>
      <el-form ref="assignform" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('cons.unitName')">
              {{ form.name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('cons.machine')" prop="toMachineId">
              <el-select style="width: 100%" v-model="form.machineId" multiple
                         :placeholder="$t('common.select',{name:$t('cons.machine')})">
                <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">{{ $t('common.confirm') }}</el-button>
        <el-button @click="assignDialog.open = false">{{ $t('common.cancel') }}</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";
import {NodeType} from "@/utils/EnumConst";

export default {
  name: "cons-unit",
  computed: {
    NodeType() {
      return NodeType
    }
  },
  dicts: ['cons_unit_type', 'classify_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: this.$t("common.required", {name: this.$t('cons.parentUnit')}), trigger: "blur"}
        ],
        name: [
          {required: true, message: this.$t("common.required", {name: this.$t('cons.unitName')}), 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.$t("tips.modifySuccess"));
            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: null,
        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 = this.$t("common.addDialog", {name: this.$t("cons.consUnit")});
      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;
        const {classifyType} = response.data;
        this.form.classifyType = classifyType && classifyType + '';
        this.open = true;
        this.title = this.$t("common.modifyDialog", {name: this.$t("cons.consUnit")});
        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.$t("tips.modifySuccess"));
              this.open = false;
              this.getList();
            });
          } else {
            addConsUnitInfo(this.form).then(response => {
              this.$modal.msgSuccess(this.$t("tips.addSuccess"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm(this.$t("tips.confirmDelete", {name: row.name})).then(function () {
        return delConsUnitInfo(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t("tips.deletedSuccess"));
      }).catch(() => {
      });
    },

    handleExport(row) {
      this.download('cons/consUnitInfo/export/cad', {
        id: row.id
      }, `attendGroup_${new Date().getTime()}.dwg`)
    },

    handleExportCsv(row) {
      this.download('cons/consUnitInfo/export/csv', {
        id: row.id
      }, `unit_construct_${new Date().getTime()}.csv`)
    },

  }
};
</script>
