<template>
  <div class="global-variable" v-loading="loading">
    <div class="condition">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="单位名称:">
          <el-input
            v-model="formInline.companyName"
            placeholder="请输入单位名称"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select
            v-model="formInline.state"
            placeholder="选择状态"
            size="small "
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableList" size="small"
            >查询</el-button
          >
          <el-button @click="reset" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <div class="newly">
        <el-button type="primary" @click="newnuedialog" size="small"
          >新增</el-button
        >
        <el-button type="primary" @click="toggleExpandAll" size="small">{{
          defaultExpandAll ? "收起" : "展开"
        }}</el-button>
      </div>

      <el-table
        class="center-align-table"
        ref="table"
        :data="tableData"
        border
        stripe
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- Table Columns -->
        <el-table-column prop="codeName" align="left" label="单位名称">
        </el-table-column>
        <el-table-column prop="companyCode" align="center" label="单位ID">
        </el-table-column>

        <el-table-column
          prop="fieldCount"
          align="center"
          label="风场数量"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button @click="particulars(scope.row)" type="text" size="small">
              {{ scope.row.fieldCount ? scope.row.fieldCount : 0 }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          prop="state"
          align="center"
          label="状态"
          min-width="200"
        >
          <template slot-scope="{ row }">
            {{ row.state == 1 ? "启用" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
          <template slot-scope="{ row }">
            {{ $formatDateTWO(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          align="center"
          fixed="right"
          label="操作"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button @click="compile(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button
              @click="newcomer(scope.row, 'addChild')"
              type="text"
              size="small"
              >新增</el-button
            >
            <el-button
              v-if="scope.row.state == 0"
              @click="start(scope.row, 1)"
              type="text"
              size="small"
              >启用</el-button
            >
            <el-button
              v-else
              style="color: #666"
              @click="start(scope.row, 0)"
              type="text"
              size="small"
              >停用</el-button
            >
            <el-button
              style="color: #f00"
              @click="deleted(scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹出层 -->
    <!-- 新增 -->
    <el-dialog
      :title="title"
      :visible.sync="nuedialog"
      width="380px"
      @close="handleClose"
    >
      <el-form
        ref="newform"
        :rules="rules"
        :model="newform"
        label-width="90px"
        class="form-margin"
      >
        <el-form-item label="单位名称:" prop="companyName">
          <el-input v-model="newform.companyName" size="small"></el-input>
        </el-form-item>
        <el-form-item label="所属省:" prop="province">
          <el-select
            v-model="newform.province"
            placeholder="请选择"
            size="small"
            value-key="areaId"
            @change="fetchCities"
          >
            <el-option
              v-for="item in shengdata"
              :key="item.areaId"
              :label="item.province"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属市:" prop="city">
          <el-select
            v-model="newform.city"
            placeholder="请选择"
            size="small"
            value-key="areaId"
            @change="$forceUpdate()"
          >
            <el-option
              v-for="item in shidata"
              :key="item.areaId"
              :label="item.city"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            v-model="newform.described"
            size="small"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="nuedialog = false" size="small">取 消</el-button>
        <el-button type="primary" @click="newly('newform')" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 风场数量 -->
    <el-dialog title="风场数量" :visible.sync="unusualdialog" width="1000px">
      <el-table
        class="center-align-table"
        :data="FCtableData"
        border
        :cell-style="rowStyle"
        stripe
        max-height="500"
      >
        <!-- Table Columns -->
        <el-table-column
          fixed
          prop="fieldName"
          align="center"
          label="风场名称"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="provinceName"
          align="center"
          label="所在省"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="cityName"
          align="center"
          label="所在市"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="elevationHeight"
          align="center"
          label="海拔高度/米"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="longitude"
          align="center"
          label="经度"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="latitude"
          align="center"
          label="纬度"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="ratedCapacityNumber"
          align="center"
          label="额定容量/kW"
          min-width="100"
        >
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <!-- <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="pageNum"
          layout="total, prev, pager, next"
          :page-size="pageSize"
          :total="totalSize"
        >
        </el-pagination> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
import {
  getAllWindCompany,
  addCompany,
  updateCompany,
  updateStateCompany,
  findAllProvince,
  getCitiesByPId,
  getWindCompany,
  delCompany,
  getWindFieldVos,
} from "@/api/ledger.js";
export default {
  data() {
    return {
      loading: false,
      // 查询
      formInline: {
        companyName: "",
        state: "",
      },
      // 新增
      newform: {
        parentCode: "",
        companyName: "",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        described: "",
      },
      shengdata: [],
      shidata: [],
      defaultExpandAll: true,

      rules: {
        companyName: [
          { required: true, message: "请填写单位名称", trigger: "blur,change" },
        ],
        province: [{ required: true, message: "请选择省", trigger: "change" }],
        city: [{ required: true, message: "请选择市", trigger: "change" }],
      },
      tableData: [],
      FCtableData: [],
      detail: {},
      nuedialog: false,
      unusualdialog: false,
      isEdit: false,
      title: "新增",
      warningShown: false,
      addPrarentCompanyCode: null,
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
    };
  },
  created() {
    this.getTableList();
    this.postsheng();
  },
  watch: {
    tableData: {
      handler(newData) {
        this.$nextTick(() => {
          this.setExpandAll(this.defaultExpandAll);
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    handleClose() {
      Object.assign(this.newform, {
        companyName: "",
        province: null,
        city: null,
        described: "",
      });
      this.$refs.newform.resetFields();
    },

    rowStyle() {
      return "text-align:center";
    },

    // 查询
    getTableList() {
      let objectval;

      if (this.formInline.companyName === "" && this.formInline.state === "") {
        objectval = {};
      } else {
        objectval = {
          companyName: this.formInline.companyName,
          state: this.formInline.state,
        };
      }
      this.loading = true;
      getAllWindCompany(objectval)
        .then((res) => {
          this.tableData = res.data;
          this.loading = false;
        })
        .catch((error) => {
          console.error(error, "error");
          this.loading = false;
        });
    },

    // 重置
    reset() {
      this.formInline.companyName = "";
      this.formInline.state = "";
      this.newform.companyName = "";
      this.newform.province = "";
      this.newform.city = "";
      this.newform.described = "";

      getAllWindCompany({
        companyName: "",
        state: "",
      }).then((res) => {
        this.tableData = res.data;
      });
    },

    // 启用/停用
    start(row, type) {
      let objectval = {
        companyCode: row.companyCode,
        state: type === 0 ? 0 : 1,
      };
      updateStateCompany(objectval).then((res) => {
        this.$message({
          message: "状态已更新成功",
          type: "success",
        });
        // this.$message(`${type === 1 ? '状态已更新成功' : '状态已更新成功'}`);
        row.state = type === 1 ? 0 : 1;
        this.getTableList();
      });
    },

    // 省份
    postsheng() {
      findAllProvince().then((res) => {
        this.shengdata = res.data;
      });
    },
    // 市
    fetchCities(item, city) {
      console.log(item, this.newform.province);
      this.newform.province = item;
      let data = {
        provinceId: item.areaId,
      };
      getCitiesByPId(data).then((res) => {
        this.shidata = res.data;
      });
      if (city) {
        this.newform.city = Object.assign(
          {},
          { areaId: city.areaId, city: city.city }
        );
      }
    },
    // 新增提交
    newly(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let objectval = {
            parentCode: this.addPrarentCompanyCode || 0, // 一级单位默认传0
            companyName: this.newform?.companyName, // 企业名称
            provinceId: this.newform.province?.areaId, // 省
            provinceName: this.newform.province?.province,
            cityId: this.newform.city?.areaId, // 市
            cityName: this.newform.city?.city,
            described: this.newform?.described, // 备注
          };

          let requestPromise;
          if (!this.isEdit) {
            requestPromise = addCompany(objectval);
          } else {
            objectval.companyCode = this.detail.companyCode;
            delete objectval.parentCode;
            requestPromise = updateCompany(objectval);
          }

          requestPromise
            .then((res) => {
              this.addPrarentCompanyCode = null;
              if (this.isEdit) {
                this.isEdit = false;
              }
              if (res.code === -1) {
                this.$message({
                  message: "操作失败",
                  type: "error",
                });
              } else {
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
              }
              this.nuedialog = false;
              this.getTableList();
            })
            .catch((error) => {
              console.error(error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 新增触发 一级新增
    newnuedialog() {
      this.nuedialog = true;
      this.title = "新增";
    },

    // 新增子级 这是二级入口
    newcomer(row, type) {
      this.nuedialog = true;
      this.addPrarentCompanyCode = row.companyCode;
      this.title = "新增子单位";
    },

    // 删除
    deleted(row) {
      console.log(row, "row");
      if (row.state == "1") {
        this.$message({
          type: "error",
          message: "该项处于启用状态，无法删除！",
        });
        return;
      }
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delCompany({ companyCode: row.companyCode })
            .then((res) => {
              if (res.code === -1) {
                // Adjust based on your API response for a successful delete
                this.$message({
                  type: "error",
                  message: "删除失败！",
                });
              } else {
                this.$message({
                  type: "success",
                  message: "删除成功！",
                });
                this.getTableList();
              }
            })
            .catch((error) => {
              console.error(error);
            });
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展开收起
    toggleExpandAll() {
      this.defaultExpandAll = !this.defaultExpandAll;
      this.$nextTick(() => {
        this.setExpandAll(this.defaultExpandAll);
      });
    },

    setExpandAll(expand) {
      const table = this.$refs.table;
      if (table) {
        this.tableData.forEach((row) => {
          table.toggleRowExpansion(row, expand);
          if (row.children) {
            row.children.forEach((child) => {
              table.toggleRowExpansion(child, expand);
            });
          }
        });
      }
    },

    //查看风场信息
    particulars(row) {
      this.unusualdialog = true;
      // const arr = {
      //   companyCode: "arr",
      // };
      getWindFieldVos({ companyCode: row.companyCode }).then((res) => {
        this.FCtableData = res.data;
        this.totalSize = res.totalSize;
      });
    },
    // handleCurrentChange(val) {
    //   this.pageNum = val;
    //   this.getTableList();
    // },
    // 编辑回显
    compile(row) {
      this.title = "编辑";
      this.isEdit = true;
      getWindCompany({
        companyCode: row.companyCode,
      }).then((res) => {
        const item = JSON.parse(JSON.stringify(res.data));
        this.detail = item;
        this.newform = Object.assign(
          {},
          {
            companyName: item.companyName,
            described: item.described,
          }
        );
        this.newform.province = Object.assign(
          {},
          { areaId: item.provinceId, provice: item.provinceName }
        );
        let that = this;
        // this.newform.city = Object.assign({}, { areaId: item.cityId, city: item.cityName });
        this.fetchCities(this.newform.province, {
          areaId: item.cityId,
          city: item.cityName,
        });
        console.log(this.newform, row, item);
        this.nuedialog = true;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 250px;
}

.form-margin {
  .el-form-item {
    margin-bottom: 22px;
  }
}
</style>
