<template>
  <div class="app-container iot-project">
    <component :is="componectVal" :sourceId="sourceId"></component>

    <div v-show="componectVal === ''">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="industry">
          <el-select v-model="queryParams.industry" placeholder="请选择项目类型" clearable size="small">
            <el-option
              v-for="dict in projectTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></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="['iot:project:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="projectList"
        :default-sort="{prop: 'createTime', order: 'descending'}"
        @sort-change="sortChange"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          :index="indexFormatter"
          width="80px"
        ></el-table-column>
        <el-table-column label="项目名称" width="200px" align="left" prop="projectName" />
        <el-table-column
          label="项目类型"
          align="center"
          width="150"
          :formatter="statusFormat"
          prop="industry"
        />
        <el-table-column label="行政区划" align="left" width="250" prop="regionalismFullName" />
        <el-table-column label="项目地址" align="left" prop="projectAddress" >
          <template slot-scope="scope">
            <span class="lay-table-textarea" :title="scope.row.projectAddress">
              {{ scope.row.projectAddress }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          sortable="custom"
          align="center"
          width="160"
          prop="createTime"
        />
        <el-table-column
          label="操作"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-search"
              @click="handleDetails(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['iot:project:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['iot:project: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-dialog class="eldialog-wrap" :close-on-click-modal="false" :title="title" :visible.sync="open" width="720px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称:" prop="projectName">
                <el-input v-model="form.projectName" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="项目类型:" prop="industry">
                <el-select v-model="form.industry" style="width: 100%;" placeholder="请选择项目类型">
                  <el-option
                    v-for="dict in projectTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="电价合同:" >
            <el-input v-model="form.contractName" suffix-icon="el-icon-caret-bottom"  @focus="inputFocusContract()" placeholder="请输入电价合同" />
          </el-form-item>


          <el-form-item label="行政区划" prop="regionalismId">
            <!-- <el-input v-model="form.regionalismId" placeholder="请输入行政区划代码" /> -->
            <treeselect
              @select="regionalismChange"
              :disable-branch-nodes="true"
              v-model="form.regionalismId"
              :options="regionalismOption"
              :normalizer="normalizer"
              placeholder="请选择上级行政区划"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目经度" prop="projectLng">
                <el-input v-model="form.projectLng" disabled placeholder="请输入项目经度" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="项目纬度" prop="projectLat">
                <el-input v-model="form.projectLat" disabled placeholder="请输入项目纬度" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="项目地址" prop="projectAddress">
                <el-input
                  v-model="form.projectAddress"
                  @blur="mapAddressFromPoint"
                  placeholder="请输入项目地址"
                >
                  <el-popover
                    slot="suffix"
                    placement="left-start"
                    title="地图选择坐标"
                    width="730"
                    trigger="manual"
                    v-model="visible"
                  >
                    <i slot="reference" class="el-icon-map-location" @click="mapClick"></i>
                    <!-- 地图模块选择和设置 -->
                    <slot>
                      <el-row>
                        <el-col :span="7">
                          <span>经度：{{mapForm.lng}}</span>
                        </el-col>
                        <el-col :span="7">
                          <span>纬度：{{mapForm.lat}}</span>
                        </el-col>
                        <el-col :span="10">
                          <span>地址：{{mapForm.address}}</span>
                        </el-col>
                      </el-row>

                      <shop-location
                        v-if="visible === true"
                        style="height: 300px;"
                        :mapCenter="mapCenter"
                        :draggable="true"
                        @mapEvent="mapEvent"
                        :zoom="zoom"
                      />

                      <div
                        style="
                          width: 100%;
                          height: 50px;
                          display: flex;
                          align-items: center;
                          justify-content: flex-end;
                          margin-top: 5px;
                          "
                      >
                        <el-button type="primary" @click="mapSureClick">确 定</el-button>
                        <el-button @click="visible = false">取 消</el-button>
                      </div>
                    </slot>
                  </el-popover>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="总路设备:" >
            <el-input v-model="form.projectDeviceName" suffix-icon="el-icon-caret-bottom"  @focus="openTableSelectDialog()" placeholder="请输入总路设备" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="mini" @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <el-dialog
      title="选择"
      :visible.sync="selectTableShow"
      width="75%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
    >
      <select-table-wrap
        v-if="selectTableShow"
        :tableOption="tableSelectOption.tableOpt"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        @parentGetList="childGetList($event)"
        :otherOption="tableSelectOption.otherOption"
        @returnEvent="returnEvent($event)"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="resultClick">确 定</el-button>
        <el-button size="mini" @click="() =>{selectTableShow = false}">取 消</el-button>
      </div>
    </el-dialog>

    <div class="to-home-wrap2" @click="toTableClick" v-show="componectVal !== ''">
      <el-button icon="el-icon-d-arrow-left" title="返回列表" circle>返回列表</el-button>
    </div>
  </div>
</template>

<script>
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  exportProject
} from "@/api/iot/project";
import {
  listDevice
} from "@/api/iot/device";
import {
  listContract
} from "@/api/iot/contract";
import { listRegionalism } from "@/api/system/regionalism";
import { initMap, gjzCode } from "@/utils/latlngFromAddress.js";
import ShopLocation from "@/components/Amap/components/shopLocation/index";
import DetailsWrap from "./profile/details";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectTableWrap from "@/components/SelectTable/index";

export default {
  name: "Project",
  components: {
    ShopLocation,
    Treeselect,
    DetailsWrap,
    SelectTableWrap
  },
  data() {
    return {
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        industry: null,
        regionalismId: null,
        projectAddress: null,
        projectStatus: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        industry: [
          { required: true, message: "项目类型不能为空", trigger: "blur" }
        ],
        regionalismId: [
          { required: true, message: "行政区划不能为空", trigger: "change" }
        ],
        projectAddress: [
          { required: true, message: "项目地址不能为空", trigger: "change" }
        ],
        projectLng: [
          { required: true, message: "经度不能为空", trigger: "change" }
        ],
        projectLat: [
          { required: true, message: "纬度不能为空", trigger: "change" }
        ]
      },
      projectTypeOptions: [],
      mapCenter: {
        lng: 119.459889,
        lat: 25.98974
      },
      baiduMapKey: "N05AG95Umzs3fouk6WpFqtGxcDlw0fRn",
      zoom: 15,
      BMap: null,
      map: null,
      visible: false,
      mapForm: {},
      // 行政划分树选项
      regionalismOption: [],
      componectVal: "",
      sourceId: ""
    };
  },
  created() {
    if (this.$route.query['projectId']) {
      this.handleDetails(this.$route.query)
    }
    this.getDicts("project_industry").then(response => {
      this.projectTypeOptions = response.data;
    });
    this.getList();
    this.getTreeselect();
  },
  methods: {
     // 打开设备选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            deviceName: "",
            modelId: "",
            parentId: 0,
            deviceType: "MINIATURE_BREAKER"
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "设备名称",
              clearable: true,
              label: "设备名称",
              type: "input",
              key: "deviceName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "所属型号",
              type: "",
              prop: "modelName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备名称",
              type: "",
              prop: "deviceName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备Key",
              type: "",
              prop: "deviceKey",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "创建时间",
              type: "time",
              prop: "createTime",
              align: "center",
              width: "160",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    // 开启 电价合同选择的 弹窗
    inputFocusContract() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "model"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            contractName: "",
            modelCode: ""
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "合同名称",
              clearable: true,
              label: "合同名称",
              type: "input",
              key: "contractName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "合同名称",
              type: "",
              prop: "contractName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "计价类型",
              type: "",
              prop: "contractType",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "strType",
              option: {
                PEAK_VALLEY: "峰谷时段计价",
                LADDER: "阶梯计价"
              }
            },
            {
              style: "",
              label: "状态",
              type: "",
              prop: "status",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "text1"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      if (data.otherOption.tableType === "device") {
        this.deviceChildList(data);
      } else if (data.otherOption.tableType === "model") {
        this.getListContract(data);
      }
    },
    // 电价合同查询
    getListContract(data) {
      listContract(Object.assign(data.page, data.param, { selected: 1 })).then(
        response => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    deviceChildList(data) {
      listDevice(Object.assign(data.page, data.param, { selected: 1 })).then(
        response => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        if (data.otherOption.tableType === "device") {
          this.form.projectDevice = data.value.deviceId;
          this.form.projectDeviceName = data.value.deviceName;
        } else if (data.otherOption.tableType === "model") {
          this.form.contractId = data.value.contractId;
          this.form.contractName = data.value.contractName;
        }
        this.selectTableShow = false;
      } else if (data.type === "click") {
        this.selectResult = {};
        if (data.otherOption.tableType === "device") {
          this.selectResult.projectDevice = data.value.deviceId;
          this.selectResult.projectDeviceName = data.value.deviceName;
        } else if (data.otherOption.tableType === "model") {
          this.selectResult.contractId = data.value.contractId;
          this.selectResult.contractName = data.value.contractName;
        }
        this.selectResult.tableType = data.otherOption.tableType;
      }
    },
    // 点击确定按钮
    resultClick() {
      if (this.selectResult.tableType === "device") {
        this.form.projectDevice = this.selectResult.projectDevice;
        this.form.projectDeviceName = this.selectResult.projectDeviceName;
      } else if (this.selectResult.tableType === "model") {
        this.form.contractId = this.selectResult.contractId;
        this.form.contractName = this.selectResult.contractName;
      }
      this.selectTableShow = false;
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    handleDetails(row) {
      this.sourceId = row.projectId;
      this.componectVal = "DetailsWrap";
    },
    // 跳转详情页
    toTableClick() {
      if (this.$route.query['projectId']) {
        this.$router.push('/project/project')
      }
      this.componectVal = "";
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.projectTypeOptions, row.industry);
    },
    /** 查询行政区划下拉树结构 */
    getTreeselect() {
      listRegionalism().then(response => {
        this.regionalismOption = [];
        const data = {
          regionalismId: 0,
          regionalismName: "中国",
          children: []
        };
        data.children = this.handleTree(
          response.data,
          "regionalismId",
          "parentId"
        );
        this.regionalismOption.push(data);
      });
    },
    /** 转换行政划分数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.regionalismId,
        label: node.regionalismName,
        children: node.children
      };
    },
    regionalismChange(val) {
      this.mapCenter = {
        lng: val.stationLng,
        lat: val.stationLat
      };
      this.form.projectLng = val.stationLng;
      this.form.projectLat = val.stationLat;
    },
    // 地图方法
    handler({ BMap, map }) {
      //地图
      this.BMap = BMap;
      this.map = map;
      this.mapLoading = false;
      // this.getPointByIp()
    },
    mapEvent(data) {
      this.mapForm.lng = data.lng;
      this.mapForm.lat = data.lat;
      this.mapForm.address = data.address;
      this.$forceUpdate();
    },
    // 使用地图方式定位
    mapClick() {
      if (this.form.projectLng && this.form.projectLat) {
        this.mapCenter.lng = this.form.projectLng;
        this.mapCenter.lat = this.form.projectLat;
        this.mapForm.lng = this.form.projectLng;
        this.mapForm.lat = this.form.projectLat;
        this.mapForm.address = this.form.projectAddress;
      } else {
        this.mapCenter = {
          lng: 119.459889,
          lat: 25.98974
        };
        this.mapForm.lng = 119.459889;
        this.mapForm.lat = 25.98974;
        this.mapForm.address = "";
      }
      this.visible = !this.visible;
    },
    mapSureClick() {
      // 确认的时候将值赋值给form表单并且关闭地图
      this.form.projectAddress = this.mapForm.address
        ? this.mapForm.address
        : this.form.projectAddress;
      this.form.projectLng = this.mapForm.lng;
      this.form.projectLat = this.mapForm.lat;
      this.visible = false;
    },
    mapAddressFromPoint() {
      if (this.form.projectAddress) {
        // geoCode(this.form.projectAddress, this, { form: 'form', lat: 'shopLat', lng: 'shopLng' })
        gjzCode(this.form.projectAddress, this, {
          form: "form",
          lat: "shopLat",
          lng: "shopLng"
        });
      }
    },

    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectName: null,
        industry: null,
        regionalismId: null,
        projectAddress: null,
        projectLng: null,
        projectLat: null,
        projectDevice: '',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids;
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delProject(projectIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有项目数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportProject(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
<style lang="scss">
.iot-project {
  .eldialog-wrap {
    .el-dialog__header {
      border-bottom: 1px solid #747373;
    }
    .el-dialog__body {
      padding: 0px;
    }
    .el-form {
      padding: 20px;
      padding-right: 40px;
    }
    .el-dialog__footer {
      height: 60px;
      border-top: 1px solid #747373;
      text-align: right;
      width: 100%;
      padding: 0px;
      padding-top: 15px;
      .el-button + .el-button {
        margin-right: 10px;
      }
      .el-button {
        padding-top: 8px;
      }
    }
  }
  .to-home-wrap2 {
    width: 20px;
    height: 20px;
    position: absolute;
    right: 30px;
    top: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
    color: #656363;
    font-size: 20px;
    cursor: default;
    width: 100px;
    .el-button--medium.is-circle {
      width: 25px;
      height: 20px;
      padding: 0;
      background: #f26a6a;
      color: #fff;
      font-size: 16px;
      border-radius: 5px;
      height: 30px;
      width: 100%;
      font-size: 14px;
    }
  }
  .to-home-wrap2:hover {
    color: #1890ff;
    font-size: 30px;
  }
}
</style>
