<template>
  <div class="app-container prj-pit-config">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="queryParams.projectId" filterable placeholder="请选择项目" clearable
          @change="doQuerySub('query')">
          <el-option v-for="(item, index) in projectOptions" :key="index" :label="item.projectName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总包单位" prop="subDeptId">
        <el-select v-model="queryParams.subDeptId" filterable placeholder="请选择总包单位" clearable>
          <el-option v-for="(item, index) in depts" :key="index" :label="item.deptName" :value="item.deptId">
          </el-option>
        </el-select>
      </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="['device:pitConfig:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['device:pitConfig:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['device:pitConfig:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5" v-if="1 == 2">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['device:pitConfig:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pitConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="总包单位" align="center" prop="deptName" />
      <el-table-column label="对接厂商" align="center" prop="vendorCode" />
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.enabled == 1">启用</el-button>
          <el-button type="text" disabled v-if="scope.row.enabled == 0">停用</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" 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="['device:pitConfig:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['device:pitConfig:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目基坑监测配置
对话框 -->
    <el-drawer v-if="open" :visible.sync="open" direction="rtl" size="60%" :title="title">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="padding:0px 20px">
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="form.projectId" filterable placeholder="请选择项目" style="width:300px;" clearable
            @change="doQuerySub('dlg')">
            <el-option v-for="(item, index) in projectOptions" :key="index" :label="item.projectName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总包单位" prop="subDeptId">
          <el-select v-model="form.subDeptId" filterable placeholder="请选择总包单位" style="width:300px;" clearable
            @change="doQueryCfg">
            <el-option v-for="(item, index) in dlgDepts" :key="index" :label="item.deptName" :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-tabs type="card" v-model="form.vendorCode">
          <el-tab-pane :label="it.label" :name="it.value" v-for="(it, idx) in dict.type.pitmonit_vendors" :key="idx">
            <el-form-item label="工程编号" prop="orgId">
              <el-input v-model="form.orgId"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="identifier">
              <el-input v-model="form.identifier" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="credential">
              <el-input v-model="form.credential"></el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch v-model="form.enabled" active-color="#13ce66" inactive-color="#ccc">
          </el-switch>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listPitConfig, getPitConfig, delPitConfig, addPitConfig, updatePitConfig, findByProjIdDeptId } from "@/api/device/pitConfig";

export default {
  name: "PitConfig",
  dicts: ['pitmonit_vendors'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目基坑监测配置表格数据
      pitConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        subDeptId: null,
        vendorCode: null,
        vendorParamter: null,
        enabled: null,
        state: null,
        isDel: null,
      },
      // 表单参数
      form: {
        projectId:null,
        subDeptId:null,
        orgId:'',
        identifier:'',
        credential:'',
        enabled:true
      },
      // 表单校验
      rules: {
        projectId: [{ required: true, message: "请输入工程编号", trigger: "blur" }],
        subDeptId: [{ required: true, message: "请输入工程编号", trigger: "blur" }],
        orgId: [{ required: true, message: "请输入工程编号", trigger: "blur" }],
        identifier: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        credential: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      projectOptions: [],
      depts: [],
      dlgDepts: []
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    doQueryCfg() {
      if (this.form.projectId && this.form.subDeptId) {
        findByProjIdDeptId(this.form.projectId, this.form.subDeptId).then(d => {
          let row = d.rows && d.rows.length > 0 ? d.rows[0] : null;
          if (row) {
            this.handleUpdate(row, true);
          }
        });
      }
    },
    doQuerySub(type, cb) {
      let prjId = type == "query" ? this.queryParams.projectId : this.form.projectId;
      if (!prjId) {
        if (type == "query") {
          this.depts = [];
          this.queryParams.subDeptId = ""
        } else {
          this.dlgDepts = [];
          this.form.subDeptId = ""
        }
        if (cb) cb();
        return;
      }
      let tmps = this.prjDept2 && this.prjDept2[prjId] ? this.prjDept2[prjId] || [] : [];
      if (tmps.length > 0) {
        if (type == 'query') {
          this.depts = tmps;
          this.queryParams.subDeptId = tmps.length == 1 ? tmps[0].deptId : '';
        } else {
          this.dlgDepts = tmps;
          this.form.subDeptId = tmps.length == 1 ? tmps[0].deptId : '';
          this.doQueryCfg();
        }
        if (cb) cb();
        return;
      }
      this.$api.publics.queryUnitList({
        projectId: prjId,
        unitTypes: "2".split(","),
      }).then((d) => {
        let objs = d.rows || [];
        if (!this.prjDept2) {
          this.prjDept2 = {};
        }
        this.prjDept2[prjId] = objs;
        let tmps = objs;
        if (type == 'query') {
          this.depts = tmps;
          this.queryParams.subDeptId = tmps.length == 1 ? tmps[0].deptId : '';
        } else {
          this.dlgDepts = tmps;
          this.form.subDeptId = tmps.length == 1 ? tmps[0].deptId : '';
          this.doQueryCfg();
        }
        if (cb) cb();
      });
    },
    init() {
      if (this.projectOptions && this.projectOptions.length > 0) {
        return;
      }
      this.$api.publics.getMyProjectList({}).then((response) => {
        this.projectOptions = response.rows;
      });
    },
    /** 查询项目基坑监测配置列表 */
    getList() {
      this.loading = true;
      listPitConfig(this.queryParams).then(response => {
        this.pitConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        subDeptId: null,
        vendorCode: null,
        vendorParamter: null,
        orgId:'',
        identifier:'',
        credential:'',
        enabled: true,
        state: null,
        remark: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目基坑监测配置";
      this.form.vendorCode = this.dict.type.pitmonit_vendors[0].value;
    },
    /** 修改按钮操作 */
    handleUpdate(row, fromAdd) {
      this.reset();
      this.form = {...row,orgId:'',
        identifier:'',
        credential:'',};
      let oldDeptId = this.form.subDeptId;
      if (!fromAdd) {
        this.doQuerySub("dlg", () => {
          this.form.subDeptId = oldDeptId;
        });
      }
      let param = this.$tryToJson(this.form.vendorParamter, {});
      this.form.orgId = param.orgId || "";
      this.form.identifier = param.identifier || "";
      this.form.credential = param.credential || "";
      this.form.enabled=row.enabled==1;
      this.open = true;
      this.title = "修改项目基坑监测配置";

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let param = {
            orgId: this.form.orgId,
            identifier: this.form.identifier,
            credential: this.form.credential
          };
          var postData = {
            projectId: this.form.projectId,
            subDeptId: this.form.subDeptId,
            vendorCode: this.form.vendorCode,
            enabled: this.form.enabled ? 1 : 0,
            vendorParamter: JSON.stringify(param)
          };
          if (this.form.id != null) {
            postData.id = this.form.id;
            updatePitConfig(postData).then(response => {
              this.$modal.msgSuccess("修改配置成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPitConfig(postData).then(response => {
              this.$modal.msgSuccess("新增配置成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目基坑监测配置编号为"' + ids + '"的数据项？').then(function () {
        return delPitConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/pitConfig/export', {
        ...this.queryParams
      }, `pitConfig_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.prj-pit-config {
  .el-drawer {
    .el-drawer__body {
      position: relative;

      .dialog-footer {
        position: fixed;
        bottom: 0px;
        padding: 20px;
      }
    }
  }
}
</style>
