<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :top-list="topList"
      :moren="moren"
    />
    <div v-if="topList[0].changed == true">

      <div class="thetopbox">
        <el-form ref="form1" :model="queryParams" label-width="auto">
          <el-row style="margin-left: 30px">
            <el-col :span="4">
              <el-form-item :label="'地区名称'" prop="label">
                <el-input v-model="queryParams.regionName" clearable />
              </el-form-item>

            </el-col>
            <el-col :span="4" style="margin-left: 30px;">
              <div class="searchbox">
                <el-button
                  class="my_search"
                  @click="getarealist()"
                > {{ '搜索' }}</el-button>
                <el-button class="my_reset" @click="reChongzhi"> {{ '重置' }}</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="main">
        <div class="maintop">
          <div class="mainbtn">
            <el-button
              size="small"
              class="thebtn1"
              @click="adddate()"
              v-has-buttons="['ihgConfigListAdd']"
            >{{'添加'}}</el-button>
          </div>
        </div>
        <div class="maintable">
          <el-table
            ref="table1"
            style="width: 100%"
            :header-cell-style="{ background: '#EEEEEE' }"
            :row-class-name="tableRowClassName"
            :data="tableData"
            v-loading="loading"
            row-key="pkId"
            height="715px"
            lazy
            :load="load"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            >
            <el-table-column type="selection" width="55" />

            <el-table-column
              align="center"
              prop="sort"
              :label="'序号'"
              width="300"
            />
            <el-table-column :formatter="driverNameFormat" align="center" prop="regionName" :label="'洲际名称'" />

            <el-table-column
              align="center"
              prop="time"
              :label="'操作'"
              fixed="right"
              width="280"
            >
              <template slot-scope="scope">
                <!-- 国家按钮  !-->
                <div v-if="scope.row.pkParentId==0 && scope.row.regionType==1">
                  <el-button
                    style="color: #6962F6"
                    class="button"
                    type="text"
                    size="small"
                    @click.native.prevent="update(scope.row, tableData)"
                    v-has-buttons="['ihgConfigListUpdate']"
                  >
                    {{ '修改' }}
                  </el-button>
                  <el-button
                    style="color: #3181E5"
                    class="button"
                    type="text"
                    v-has-buttons="['ihgConfigListAdd']"
                    size="small"
                    @click.native.prevent="addRow(scope.row, tableData)"
                  >
                    {{'新增'}}
                  </el-button>
                  <el-button
                    class="button"
                    type="text"
                    size="small"
                    v-has-buttons="['ihgConfigListRelation']"
                    style="color: #c73030"
                    @click.native.prevent="relevance(scope.row, tableData)"
                  >
                    {{ '关联国家' }}
                  </el-button>
                </div>
                <!-- 二级洲按钮  !-->
                <div v-if="scope.row.pkParentId>0 && scope.row.regionType==1">
                  <el-button
                    style="color: #009B58"
                    class="button"
                    type="text"
                    size="small"
                    @click.native.prevent="updates(scope.row, tableData)"
                    v-has-buttons="['ihgConfigListUpdate']"
                  >
                    {{ '修改' }}
                  </el-button>
                  <el-button
                    class="button"
                    type="text"
                    size="small"
                    style="color: #c73030"
                    v-has-buttons="['ihgConfigListRelation']"
                    @click.native.prevent="relevance(scope.row, tableData)"
                  >
                    {{ '关联国家' }}
                  </el-button>
                </div>
                <!-- 三级按钮  !-->
                <div v-if="scope.row.regionType==2">
                  <el-button
                    class="button"
                    type="text"
                    size="small"
                    style="color: #999999"
                    @click.native.prevent="showTc(scope.row, tableData)"
                    v-has-buttons="['ihgConfigListRelation']"
                  >
                    {{ '取消关联' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getarealist"
      />
    </div>
    <el-dialog
      :title="'关联国家'"
      :visible.sync="updateShow2"
      width="30%"
      center
      :before-close="handleClose1"
    >
      <el-form ref="forms" :rules="rule" :model="forms" label-width="100px">
        <div class="colors" style="font-size: 12px;text-align: left">{{ '请选择需要和' }}<span style="color: #C8161D">{{ areaName }}</span>{{ '关联的国家' }}</div>
        <el-form-item :label="'关联国家'" prop="pkAreaIdList" style="margin-left:-30px">
          <el-select
            v-model="forms.pkAreaIdList"
            clearable
            :placeholder="'请选择'"
            multiple
          >
            <el-option
              v-for="item in stateList"
              :key="item.pkId"
              :label="item.shortName"
              :value="item.pkId"
            >
              <span style="float: left;">
                <img :src="item.nationalFlag1" style="width: 30px">
              </span>
              <span style="margin-left: 10px">
                {{ item.shortName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="padding-top: 30px;display: flex;justify-content: center">
        <el-button type="text" size="small" class="button-style" @click="handleClose1"> {{ '取消' }}</el-button>
        <el-button v-preventReClick="3000" type="text" size="small" class="button-style" style="margin-left: 40px;background-color: #48B2FD;" @click="submitBtn1()">
          {{ '确认' }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="'取消关联'"
      :visible.sync="updateShow1"
      width="30%"
      center
      :before-close="handleClose2"
    >
      <div style="text-align: center;padding-top: 20px">
        <img
          style="width: 75px"
          src="@/assets/images/gth.png"
          alt=""
        >
      </div>
      <div class="colors">{{'确定'}}{{'取消关联吗？'}}</div>
      <div style="padding-top: 30px;display: flex;justify-content: center">
        <el-button type="text" size="small" class="button-style" @click="handleClose2"> {{ '取消' }}</el-button>
        <el-button v-preventReClick="3000" type="text" size="small" class="button-style" style="margin-left: 40px;background-color: #48B2FD;" @click="deleteRow()">
          {{ '确认' }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="updateTitle"
      :visible.sync="updateShow"
      width="30%"
      center
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-row v-if="sortFlag">
          <el-col :span="18">
            <el-form-item :label="'序号'" prop="sort">
              <el-input
                type="number"
                v-model="form.sort"
                style="width: 300px"
                clearable
                placeholder=""
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item :label="'洲际名称'" prop="regionName">
              <el-input
                v-model="form.regionName"
                style="width: 300px"
                clearable
                placeholder=""
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="padding-top: 50px;display: flex;justify-content: center">
        <el-button type="text" size="small" class="button-style" @click="handleClose"> {{ '取消' }}</el-button>
        <el-button v-preventReClick="3000" type="text" size="small" class="button-style" style="margin-left: 40px;background-color: #48B2FD;" @click="submitBtn()">
          {{ '确认' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import topBar from '@/components/topBarRole'
import {
  countrylist,
  getContinentList,
  addContinent,
  getContinent,
  updateContinent,
  saveTwoStage,
  updateTwoStage,
  continentCancel,
  bindingCountry,
  getSonlist
} from '@/api/system'
import * as api from '@/api/notice'
import { getcountryAllList } from '@/api/exchangerate'
import { findAllArea } from '@/api/product'
import { Message } from 'element-ui'
import { deletManageArea } from '@/api/division'
import {getRouters} from "@/api/settle";
export default {
  name: 'Xzph',
  components: {
    topBar
  },
  data() {
    return {
      stateList: [],
      areaName: '',
      sortFlag: true,
      moren: 'ihgConfigList',
      topList: [
        {
          name: '洲际配置',
          path: 'ihgConfigList',
          url: 'ihgConfigList',
          changed: false
        },
        {
          name: '区域配置',
          path: 'areaConfigList',
          url: 'areaConfigList',
          changed: false
        }
      ],
      tableData: [],
      loading:false,
      multipleSelection: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        regionName: ''
      },
      maps: new Map(),
      updateShow: false,
      updateShow1: false,
      updateShow2: false,
      addOrEdit: '', // 添加还是修改 true添加 false修改
      updateTitle: '',
      form: {
        regionName: '',
        sort: ''
      },
      forms: {
        pkParentId: '',
        pkAreaIdList: []
      },
      rule: {
        pkAreaIdList: [{ required: true, message: '请选择关联国家', trigger: 'change' }]
      },
      rules: {
        regionName: [{ required: true, message: '请输入洲际名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入洲际序号', trigger: 'blur' }]
      },
      nowRow: {}, // 暂存修改的row
      rows: {}
    }
  },
  created() {
    this.getArea()
    this.getarealist()
    this.getUserRoute()
  },
  methods: {
    getUserRoute() {
      getRouters().then((res)=>{
        res.data.forEach((item)=>{
          this.topList.forEach((items)=>{
            if (item.routeName == items.url){
              items.changed = true
            }
          })
        })
      })
    },
    driverNameFormat(row) {
      return row.regionName ? row.regionName : row.shortName
    },
    getArea() {
      getcountryAllList().then((res) => {
        this.stateList = res.data
      })
    },
    handleClose2() {
      this.updateShow1 = false
    },
    submitBtn() {
      this.ruleSubmit()
    },
    showTc(row) {
      this.updateShow1 = true
      this.rows = row
      this.nowRow = row
    },
    deleteRow() {
      const row = this.rows
      continentCancel(row.pkId).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.updateShow1 = false
          if (this.nowRow.pId) {
            // 区分子父节点 父节点1 子节点空
            const { tree, treeNode, resolve } = this.maps.get(
              this.nowRow.pkParentId
            ) // 根据父级id取出对应的节点数据
            // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
            this.$set(
              this.$refs.table1.store.states.lazyTreeNodeMap,
              tree.pkId,
              []
            )
            // 实现数据的重新加载
            this.load(tree, treeNode, resolve)
          } else {
            // pId为0时重新加载表格
            this.getarealist()
          }
        } else {
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }
      })
    },
    submitBtn1() {
      this.$refs['forms'].validate(valid => {
        if (!valid) {
          return false
        } else {
          bindingCountry(this.forms).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.updateShow2 = false
              this.forms.pkAreaIdList = []
              this.forms.pkParentId = ''
              if (this.nowRow.pId) {
                // 区分子父节点 父节点1 子节点空
                const { tree, treeNode, resolve } = this.maps.get(
                  this.nowRow.pkId
                ) // 根据父级id取出对应的节点数据
                // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                this.$set(
                  this.$refs.table1.store.states.lazyTreeNodeMap,
                  tree.pkId,
                  []
                )
                // 实现数据的重新加载
                this.load(tree, treeNode, resolve)
              } else {
                // pId为0时重新加载表格
                this.getarealist()
              }
            } else {
              Message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    ruleSubmit() {
      const datas = this.form
      const that = this
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return false
        } else {
          if (this.types === 1) {
            addContinent(datas).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                that.updateShow = false
                that.form = { 'regionName': '', 'sort': '' }
                that.getarealist()
              } else {
                Message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          }
          if (this.types === 2) {
            updateContinent(this.form).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                that.updateShow = false
                that.form = { 'regionName': '', 'sort': '' }
                that.getarealist()
                if (this.nowRow.pId) {
                  // 区分子父节点 父节点1 子节点空
                  const { tree, treeNode, resolve } = this.maps.get(
                    this.nowRow.pkId
                  ) // 根据父级id取出对应的节点数据
                  // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                  this.$set(
                    this.$refs.table1.store.states.lazyTreeNodeMap,
                    tree.pkId,
                    []
                  )
                  // 实现数据的重新加载
                  this.load(tree, treeNode, resolve)
                }else{
                  this.getarealist()
                }
              } else {
                Message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          }
          if (this.types === 3) {
            const form = {
              regionName: this.form.regionName,
              pkParentId: this.form.pkParentId
            }
            saveTwoStage(form).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                that.updateShow = false
                that.form = { 'regionName': '', 'sort': '' }
                if (this.nowRow.pId) {
                  // 区分子父节点 父节点1 子节点空
                  const { tree, treeNode, resolve } = this.maps.get(
                    this.nowRow.pkId
                  ) // 根据父级id取出对应的节点数据
                  // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                  this.$set(
                    this.$refs.table1.store.states.lazyTreeNodeMap,
                    tree.pkId,
                    []
                  )
                  console.error(tree)
                  // 实现数据的重新加载
                  this.load(tree, treeNode, resolve)
                } else {
                  that.getarealist()
                }
              } else {
                Message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          }
          if (this.types === 4) {
            const form = {
              regionName: this.form.regionName,
              pkId: this.form.pkId
            }
            updateTwoStage(form).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                that.updateShow = false
                console.error(this.nowRow)
                if (this.nowRow.pId) {
                  // 区分子父节点 父节点1 子节点空
                  const { tree, treeNode, resolve } = this.maps.get(
                    this.nowRow.pkParentId
                  ) // 根据父级id取出对应的节点数据
                  // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                  this.$set(
                    this.$refs.table1.store.states.lazyTreeNodeMap,
                    tree.pkId,
                    []
                  )
                  // 实现数据的重新加载
                  this.load(tree, treeNode, resolve)
                } else {
                  that.getarealist()
                }
              } else {
                Message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          }
        }
      })
    },
    // 修改二级大州
    updates(row) {
      console.error(row)
      this.sortFlag = false
      this.updateShow = true
      this.updateTitle = '修改'
      this.types = 4
      getContinent(row.pkId).then((res) => {
        this.form.pkId = res.data.pkId
        this.form.regionName = res.data.regionName
        this.form.sort = res.data.sort
      })
      this.nowRow = row
    },
    // 修改
    update(row) {
      this.sortFlag = false
      this.updateShow = true
      this.updateTitle = '修改'
      this.types = 2
      getContinent(row.pkId).then((res) => {
        this.form.pkId = res.data.pkId
        this.form.regionName = res.data.regionName
        this.form.sort = res.data.sort
      })
      this.nowRow = row
    },
    // 表单内行添加
    addRow(row) {
      console.log('🌈', row)
      this.updateShow = true
      this.updateTitle = '添加'
      this.types = 3
      this.sortFlag = false
      // getareaDetailList({ pkId: row.pkId }).then((res) => {
      //   this.form = res.data;
      // });
      this.form.pkParentId = row.pkId
      this.nowRow = row
      // this.$refs["form"].clearValidate();
      // this.$refs["form"].resetFields();
    },
    // 添加
    adddate() {
      this.updateShow = true
      this.updateTitle = '添加'
      this.addOrEdit = 1
      this.types = 1
      // this.$refs["form"].clearValidate();
      // this.$refs["form"].resetFields();
    },
    // 重置
    reChongzhi() {
      this.queryParams.name = ''
      this.queryParams.code = ''
    },
    handleClose1() {
      this.updateShow2 = false
      this.areaName = ''
      this.forms.pkAreaIdList = []
      this.forms.pkParentId = ''
    },
    handleClose() {
      this.updateShow = false
      this.form = { 'regionName': '', 'sort': '' }
      // this.$refs["form"].clearValidate();
      // this.$refs["form"].resetFields();
      this.sortFlag = true
    },
    // 关联国家
    relevance(row) {
      this.updateShow2 = true
      this.areaName = row.regionName
      this.forms.pkParentId = row.pkId
      this.nowRow = row
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      this.maps.set(tree.pkId, { tree, treeNode, resolve })
      if (tree.pkParentId != 0 && tree.regionType == 1) {
        console.error(111)
        countrylist({ pkParentId: tree.pkId }).then((res) => {
          res.data.forEach((item) => {
            item.pId = 1
            item.hasChildren = false
          })
          resolve(res.data)
        })
      }
      if (tree.pkParentId == 0 && tree.regionType == 1) {
        getSonlist({ pkParentId: tree.pkId }).then((res) => {
          res.data.forEach((item) => {
            item.pId = 1
            if(item.isExist==0){
              item.hasChildren = true
            }else{
              item.hasChildren = false
            }
          })
          resolve(res.data)
        })
      }
    },
    // 获取全部地区列表
    getarealist() {
      this.loading = true
      getContinentList(this.queryParams).then((res) => {
        res.rows.forEach((item) => {
          item.pId = 1
          item.one = 1
          // 是否有下一级的id
          console.error(item)
          item.hasChildren = true
        })
        this.tableData = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row'
      } else if (rowIndex % 2 == 0) {
        return 'success-row'
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
.colors{
  padding: 10px 0;
  text-align: center;
  color: #333;
  font-size: 18px;
}
::v-deep .el-dialog__header{
  padding-bottom: 20px;
}
  ::v-deep .el-dialog__title{
    font-weight: bold;
  }
  .button-style{
    width: 209px;
    height: 48px;
    background: #CCCCCC;
    border-radius: 5px 5px 5px 5px;
    opacity: 1;
    line-height: 48px;
    padding: 0!important;
    color: #fff;
    font-size: 18px;
  }
  ::v-deep .el-dialog__header{
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }
  .button-s{
    padding: 0 2px!important;
  }
::v-deep .button{
  padding: 10px 3px!important;
}
  ::v-deep .el-button{
    padding: 10px 20px;
  }
  ::v-deep .el-date-editor .el-range__close-icon{
    margin-top: -10px;
  }
  ::v-deep .el-date-editor .el-range-separator{
    margin-top: -10px;
  }
  ::v-deep .el-date-editor .el-range__icon{
    margin-top: -10px;
  }
  ::v-deep .el-input__inner{
    height:32px;
    line-height: 32px;
  }
  ::v-deep .el-form-item{
    margin-bottom: 15px;
  }
  ::v-deep .el-form-item__label{
    color: #333;
    font-weight: inherit;
  }
  ::v-deep .el-row {
    margin-top: 0px;
  }
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}

::v-deep .el-table .success-row {
  background: #ffffff;
}
::v-deep .el-table thead {
  color: #000000;
}
.page {
  padding: 10px 20px;
  background: #f9f9f9;
  font-size: 14px;
  .thetopbox {
    padding: 20px 20px 10px 20px;
    background: #ffffff;
    border-radius: 8px;

    .searchbox {
      display: flex;
      align-items: center;
      .searchtitle {
        margin-right: 10px;
      }
      .searchbtn {
        background: #08143f;
        color: #ffffff;
      }
    }
  }
  .main {
    //margin-top: 20px;
    //background: #ffffff;
    //border-radius: 8px;
    //box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);

    .maintop {
      display: flex;
      padding: 0px 0px;
      justify-content: space-between;
      align-items: center;

      .mainbtn {
        .thebtn1 {
          background: #3181e5;
          color: #ffffff;
          width: 68px;
          border-color:#3181e5 ;
        }
        .thebtn2 {
          background: #ffad41;
          color: #ffffff;
        }
      }
    }
    .maintable {
      // max-height: 550px;
      // overflow: auto;
    }
  }
}
</style>
