<template>
  <div class="customer-wrap">
    <!-- <el-radio-group v-model="btnType" size="medium" class="header-radio" @change="handleTabChange">
      <el-radio-button label="1">行政区域</el-radio-button>
      <el-radio-button label="2" :disabled="noFeature">特色区域</el-radio-button>
    </el-radio-group> -->
    <div class="draw-area-wrap wrap-first" v-if="btnType == 1">
      <section class="search-box" v-if="showSearch">
        <section class="search-cnt">
          <el-input
            v-model="areaName"
            placeholder="搜索区域"
            clearable
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
          >
          </el-input>
          <section class="search-btn" @click="handleSearch">
            <i class="el-icon-search"></i>
          </section>
        </section>
      </section>
      <div class="search-wrap">
        <el-radio-group v-model="level" size="medium" @change="onLevelChange">
          <el-radio-button label="4" :disabled="isDisable"
            >镇/街道</el-radio-button
          >
          <el-radio-button label="5">村/社区</el-radio-button>
        </el-radio-group>
        <right-toolbar
          :showSearch.sync="showSearch"
          :columns="searchColoumns"
          @queryTable="handleSearch"
          @getConfigColumns="getConfigColumns"
        ></right-toolbar>
      </div>
      <el-row>
        <el-col :span="4">
          <common-table
            v-loading="pageLoading"
            :table-data="tableData"
            :table-coloumns="tableColoumns()"
            :page-size="pageInfo.pageSize"
            :pagination="true"
            :total-rows="pageInfo.total"
            :current-page="pageInfo.pageNum"
            :isShowFilter="true"
            :configColoumns="configColoumns"
            layout="total,prev,jumper,next"
            @onPageChange="onPageChange"
            from="drawArea"
          >
            <template #operate="scope">
              <!-- <el-button type="text" size="small" class="create-btn" @click="onDetail(scope.row)"> 查看地图 </el-button> -->
              <el-button
                type="text"
                size="small"
                class="create-btn"
                @click="onPreviewCustomer(scope.row)"
              >
                查看客户
              </el-button>
            </template>
            <template #myName="scope">
              <el-button
                type="text"
                size="small"
                class="create-btn"
                @click="onDetail(scope.row)"
              >
                {{ level == "4" ? scope.row.town : scope.row.label }}</el-button
              >
            </template>
          </common-table>
        </el-col>
        <el-col :span="20">
          <div class="map-container">
            <section class="detail-info" v-if="detailModalVisible">
              <h4>
                区域详情<i
                  @click="detailModalVisible = !detailModalVisible"
                  class="el-icon-close"
                ></i>
              </h4>
              <p class="common-title">区域信息</p>
              <ul class="map-cnt" v-if="this.level === '4'">
                <li>
                  <span class="des-vl">区域编号</span>
                  <span class="des-vr">{{ mapDetailInfo.code }}</span>
                </li>
                <li>
                  <span class="des-vl">镇/街道名称</span>
                  <span class="des-vr">{{ mapDetailInfo.town }}</span>
                </li>
                <li>
                  <span class="des-vl">社区个数</span>
                  <span class="des-vr">{{ mapDetailInfo.regionCount }}</span>
                </li>
                <li>
                  <span class="des-vl">区域类型</span>
                  <span class="des-vr">{{ mapDetailInfo.regionType }}</span>
                </li>
                <li>
                  <span class="des-vl">区域规模</span>
                  <span class="des-vr">{{ mapDetailInfo.areades }}</span>
                </li>
              </ul>
              <ul class="map-cnt" v-if="this.level === '5'">
                <li>
                  <span class="des-vl">区域编号</span>
                  <span class="des-vr">{{ mapDetailInfo.code }}</span>
                </li>
                <li v-if="this.level === '5'">
                  <span class="des-vl">村/社区名称</span>
                  <span class="des-vr">{{ mapDetailInfo.label }}</span>
                </li>
                <li>
                  <span class="des-vl">所属镇/街道</span>
                  <span class="des-vr">{{ mapDetailInfo.town }}</span>
                </li>
                <li>
                  <span class="des-vl">区域类型</span>
                  <span class="des-vr">{{ mapDetailInfo.regionType }}</span>
                </li>
                <li>
                  <span class="des-vl">区域规模</span>
                  <span class="des-vr">{{ mapDetailInfo.areades }}</span>
                </li>
              </ul>
              <p class="common-title">区域备注</p>
              <el-input
                class="el-remark"
                type="textarea"
                v-if="!isEditing"
                disabled
                maxlength="100"
                :autosize="{ minRows: 2, maxRows: 4 }"
                v-model="mapDetailInfo.remark"
              ></el-input>
              <el-input
                class="el-remark"
                type="textarea"
                maxlength="100"
                v-else
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="在这里输入文本..."
                v-model="mapDetailInfo.remark"
              ></el-input>
              <div class="edit-operate">
                <el-button
                  type="plain"
                  size="small"
                  @click.prevent="onDetailModalPreview"
                  >查看客户</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  v-if="!isEditing"
                  :disabled="isEditDisable"
                  @click.prevent="isEditing = !isEditing"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  v-else
                  @click.prevent="saveEdit"
                  >保存</el-button
                >
              </div>
            </section>
            <div v-loading="mapLoading">
              <iframe
                name="bdmap"
                :src="getIframeSrc()"
                style="width: 100%; height: 600px"
              />
            </div>
          </div>
        </el-col>
      </el-row>
      <customer-modal
        ref="customerModal"
        :detailInfo="detailInfo"
        :level="level"
        btnType="1"
      ></customer-modal>
    </div>
    <div class="draw-area-wrap" v-if="btnType == 2">
      <!-- <baidu-hui-tu class="baidu-huitu" ref="bmap"/> -->
      <featured-areas ref="bmap" />
    </div>
  </div>
</template>

<script>
import CommonTable from "@/components/Common/common-table";
import {
  getRegionList,
  getRegionCoord,
  updateRegionRemark,
} from "@/api/grid/draw-area";
import CustomerModal from "./customer-modal";
import BaiduHuiTu from "../../../../map/BaiduHuiTu.vue";
import FeaturedAreas from "./components/featured-areas.vue";
import { getUserProfile } from "@/api/grid/anchor.js";
import { mapGetters } from "vuex";
import { getUserDefaultLoc } from "@/api/customRadar/customRadar.js";

export default {
  components: {
    CommonTable,
    CustomerModal,
    BaiduHuiTu,
    FeaturedAreas,
  },
  beforeRouteLeave(to, from, next) {
    this.$store.commit("SET_LAYER_INFO", {});
    this.$store.commit("SET_LEVEL", 1);
    next();
  },
  watch: {
    level: {
      handler(val) {
        this.searchColoumns = this.getSearchColoumns();
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["roles"]),
    configColumns() {
      return this.tableColoumns()?.map((ot, ind) => ({
        key: ind,
        label: ot.label,
        visible: true,
      }));
    },
    noFeature() {
      return (
        this.roles.includes("commonManager") ||
        this.roles.includes("outletAdmin")
      );
    },
  },
  data() {
    return {
      mapLoading: false,
      detailModalVisible: false,
      showSearch: true,
      pageLoading: false,
      tableData: [],
      btnType: "1",
      level: "4",
      areaName: "",
      detailInfo: {},
      searchColoumns: [],
      townColumns: [
        // {
        //   prop: 'code',
        //   label: '区域编号',
        //   align: 'left',
        // },
        {
          prop: "town",
          label: "镇/街道",
          align: "left",
          type: "myName",
        },
        // {
        //   prop: 'regionCount',
        //   label: '村/社区',
        //   align: 'left',
        // },
        // {
        //   prop: 'regionType',
        //   label: '区域类型',
        //   align: 'left',
        // },
        // {
        //   prop: 'areades',
        //   label: '区域规模',
        //   align: 'left',
        // },
        // {
        //   prop: 'remark',
        //   label: '区域备注',
        //   align: 'left',
        // },
        {
          prop: "operate",
          label: "操作",
          slotType: "operate",
          width: "200px",
          type: "slot",
        },
      ],
      areaColumns: [
        // {
        //   prop: 'code',
        //   label: '区域编码',
        //   align: 'left',
        // },
        {
          prop: "label",
          label: "村/社区",
          align: "left",
          type: "myName",
        },
        // {
        //   prop: 'town',
        //   label: '上级行政区域名称',
        //   align: 'left',
        // },
        // {
        //   prop: 'regionType',
        //   label: '区域类型',
        //   align: 'left',
        // },
        // {
        //   prop: 'areades',
        //   label: '区域规模',
        //   align: 'left',
        // },
        // {
        //   prop: 'remark',
        //   label: '区域备注',
        //   align: 'left',
        // },
        {
          prop: "operate",
          label: "操作",
          slotType: "operate",
          width: "200px",
          type: "slot",
        },
      ],
      pageInfo: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      levelMap: {
        3: "县级行政区",
        4: "乡级行政区",
        5: "村级行政区",
      },
      configColoumns: {},
      mapDetailInfo: {},
      isEditing: false,
      drawRemark: "",
      isDisable: false,
      isEditDisable: false,
    };
  },
  created() {
    window["mapProps"] = (params) => {
      // console.log(params)
      const newArr = params.split(":");
      if (newArr[0] === "SHOW_DETAIL") {
        this.mapDetailInfo = this.tableData?.find((ot) => ot.code == newArr[1]);
        // console.log(this.mapDetailInfo,'this.mapDetailInfo')
        this.detailModalVisible = true;
        // console.log(newArr[1])
        this.tableData = this.tableData.map((item) => {
          if (item.code == newArr[1]) {
            return {
              ...item,
              highLight: true,
            };
          }
          return {
            ...item,
            highLight: false,
          };
        });
      } else if (newArr[0] == "MAP_LOADING") {
        this.mapLoading = true;
      } else if (newArr[0] == "MAP_LOADING_FINISH") {
        this.mapLoading = false;
      }
    };
    this.getUser();
    const { level, btnType } = this.$route.query;
    if (level) {
      this.level = level;
      this.btnType = btnType;
      for (let key in this.$route.query) {
        delete this.$route.query[key];
      }
    }
    this.btnType = this.$route.query?.btnType || "1";
  },

  mounted() {
    if (this.btnType == 1) {
      this.initData();
    }
    // const {fromPage} = this.$route.query;
    const { layerInfo } = this.$store.state.featuredAreas;
    // console.log(layerInfo)
    if (layerInfo && layerInfo.fromPage == "approveCenter") {
      if (layerInfo?.layerId) {
        this.btnType = "2";
        this.$store.dispatch("goBack", 1);
      }
    }
  },
  methods: {
    handleTabChange(tab) {
      this.$store.commit("SET_LAYER_INFO", {});
      if (this.btnType == 1) {
        this.initData();
      } else if (this.btnType == 2) {
      }
      this.$store.dispatch("goBack", 1);
    },
    getUser() {
      const role =
        this.roles.includes("headAdmin") ||
        this.roles.includes("headOps") ||
        this.roles.includes("headPublic") ||
        this.roles.includes("headPrivate");
      if (this.btnType === 1) {
        if (role) {
          this.level = "4";
          this.isDisable = false;
        } else {
          this.level = "5";
          this.isDisable = true;
          this.isEditDisable = true;
        }
        this.initData();
      }
      // getUserProfile().then(res => {
      //   let roleName = res.data.roleName
      //   if (this.btnType === 1) {
      //     if (roleName == '总行管理员' || ) {
      //       this.level = '4'
      //       this.isDisable = false
      //     } else {
      //       this.level = '5'
      //       this.isDisable = true
      //       this.isEditDisable = true
      //     }
      //     this.initData()
      //   }
      // })
    },
    onLevelChange(val) {
      this.handleSearch();
    },
    getIframeSrc() {
      const baseUrl = "/baidu/area.html"
      const queryString = new URLSearchParams({ 'NODE_ENV': process.env.NODE_ENV }).toString()

      return `${baseUrl}?${queryString}`
    },
    getSearchColoumns() {
      const newArr = [];
      this.tableColoumns()?.map((ot, oInd) => {
        if (ot.label !== "操作") {
          newArr.push({
            key: oInd,
            label: ot.label,
            visible: true,
          });
        }
      });
      return newArr;
    },
    onDetailModalPreview() {
      this.detailInfo = this.mapDetailInfo;
      this.$refs.customerModal.onOpen();
    },
    async saveEdit() {
      const res = await updateRegionRemark({
        code: this.mapDetailInfo.code,
        remark: this.mapDetailInfo.remark,
      });
      if (res.code === 200) {
        this.$message.success(res.data);
        this.handleSearch();
      }
      // console.log(res)
    },
    startEdit(row) {
      // console.log(row)
    },
    tableColoumns() {
      if (this.level === "4") {
        return this.townColumns;
      } else {
        return this.areaColumns;
      }
    },
    async initData() {
      try {
        this.pageLoading = true;
        this.mapLoading = true;
        const result = await getRegionList({
          pageNum: this.pageInfo.pageNum,
          pageSize: this.pageInfo.pageSize,
          code: this.areaName,
          level: this.level,
        });
        this.tableData = result?.rows?.map((item) => ({
          ...item,
          level: this.levelMap[item.level],
          areades: `${item?.custBusinessCount || 0}企业, ${
            item?.custMerchantCount || 0
          }商户, ${item?.custRetailCount || 0}个人`,
          regionCount: `${item.regionCount}个`,
        }));
        this.pageInfo.total = result.total;
      } catch (error) {
        console.error(error);
      } finally {
        if (this.tableData && this.tableData.length > 0) {
          setTimeout(() => {
            this.getMapInfo(this.tableData);
          }, 1000);
        }
        this.pageLoading = false;
        this.mapLoading = false;
      }
    },
    initMap() {
      // console.log(this.tableData)
    },
    getConfigColumns(obj) {
      this.configColoumns = obj;
    },
    handleSearch() {
      this.onPageChange(1);
    },
    onPageChange(page) {
      this.pageInfo.pageNum = page;
      this.initData();
    },
    getMapInfo(data) {
      // this.mapLoading = true
      this.isEditing = false;
      const newArr = data.map((item) => {
        return {
          polygonList: item.polygonList,
          code: item.code,
        };
      });
      window.frames["bdmap"].addPolygon(newArr);
    },
    async onDetail(row) {
      // this.mapLoading = true
      this.tableData = this.tableData.map((item) => {
        if (item.code == row.code) {
          return {
            ...item,
            highLight: true,
          };
        }
        return {
          ...item,
          highLight: false,
        };
      });
      this.isEditing = false;
      this.mapDetailInfo = {
        ...row,
      };
      window.frames["bdmap"].setAllFillColor(row.code);
      this.detailModalVisible = true;
      // this.mapLoading = false
    },
    onPreviewCustomer(row) {
      this.detailInfo = row;
      this.$refs.customerModal.onOpen();
    },
    onEdit(row) {
      // console.log(row, '----------------->>>')
    },
  },
};
</script>

<style lang="scss" scoped>
.draw-area-wrap {
  padding: 20px 20px;
}
.wrap-first {
  ::v-deep .el-pagination__jump {
    margin-left: 0;
  }
}

.search-wrap {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.customer-wrap {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
}

.header-radio {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #ebebeb;

  .el-radio-button {
    flex: 1;

    ::v-deep .el-radio-button__inner {
      width: 100%;
      border: none;
      font-weight: 400;
      letter-spacing: 0.44px;
      line-height: 25px;
      font-size: 16px;
      color: #666666;
      padding: 11px 0 12px 0;
    }

    ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
      background-color: #4886f8;
      font-weight: 400;
      color: #ffffff;
      border-bottom-left-radius: 0;
      border-bottom-right-radius: 0;
    }
  }
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin: 0 0 24px 0;

  .search-cnt {
    position: relative;
    width: 70%;
  }

  ::v-deep .el-input {
    width: 100%;
    position: relative;

    .el-input__inner {
      height: 44px;
      line-height: 44px;
      border-radius: 23px;
      border: 1px solid #ebebeb;
      padding-left: 24px;
    }

    .el-input__suffix {
      right: 85px;
    }
  }

  .search-btn {
    width: 80px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 0;
    top: 2px;
    border: 1px solid #4886f8;
    background-color: #4886f8;
    border-radius: 20px;
    cursor: pointer;
    z-index: 1;

    .el-icon-search {
      color: #ffffff;
      font-size: 14px;
    }
  }
}

.plain-raido-btn {
  ::v-deep .el-radio-button__inner {
    color: #666666;
    font-size: 14px;
    font-weight: 400;
    border: 1px solid #ebebeb;
    border-radius: 0;
  }

  ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    border: 1px solid #4886f8;
    color: #4886f8;
    background-color: #ffffff;
    box-shadow: none;
  }
}

.map-container {
  position: relative;

  .common-title {
    position: relative;
    color: #ffffff;
    line-height: 16px;
    font-weight: 500;
    font-size: 16px;
    padding-left: 10px;
    margin: 24px 30px 24px 18px;

    &::before {
      position: absolute;
      top: 50%;
      transform: translatey(-50%);
      left: 0;
      content: "";
      width: 2px;
      background-color: #4886f8;
      height: 16px;
    }
  }

  .detail-info {
    background-color: rgba(0, 0, 0, 0.78);
    color: white;
    width: 390px;
    position: absolute;
    right: 40px;
    top: 40px;
    border-radius: 8px;

    h4 {
      font-size: 18px;
      color: #ffffff;
      line-height: 25px;
      font-weight: 600;
      text-align: center;
      margin: 24px 0;
      position: relative;
    }

    .el-icon-close {
      position: absolute;
      right: 24px;
      top: 0;
      font-size: 18px;
      cursor: pointer;
    }

    .map-cnt {
      margin: 0 30px;

      li {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        span {
          font-size: 14px;
          line-height: 16px;
          color: #cccccc;
        }

        .des-vl {
          width: 86px;
          text-align: right;
          margin-right: 28px;
        }

        .des-vr {
          flex: 1;
        }
      }
    }

    .edit-operate {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 12px 30px;
      border-top: 1px solid #646363;
    }

    .el-remark {
      padding: 0 30px;
      margin-bottom: 30px;

      ::v-deep .el-textarea__inner {
        background-color: #ffffff1a;
        color: #cccccc;
      }
    }
  }
}

// .baidu-huitu {
//   width: 100%;
//   height: 800px;
// }
</style>
