<template>
  <div class="page">
    <topBar v-if="topList.length > 0"
            :topList="topList"
            :moren="moren"></topBar>
    <div class="thetopbox">
      <el-form ref="form1"
               :model="queryParams"
               label-width="auto">
        <el-row>
          <el-col :span="4">
            <el-form-item :label="'地区名称'"
                          prop="label">
              <el-input clearable
                        v-model="queryParams.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="'地区编号'"
                          prop="label">
              <el-input clearable
                        v-model="queryParams.code"></el-input>
            </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"
                     style="border-color: #3181e5"
                     @click="adddate()"
                     v-has-buttons="['DivisionAdd']">{{'添加'}}</el-button>
          <el-button v-has-buttons="['DivisionExport']"
                     size="small"
                     style="border-color: #ffad41; margin-left: 20px"
                     @click="exports()"
                     class="thebtn2"> {{ '导出' }}</el-button>
        </div>
      </div>
      <div class="maintable">
        <el-table style="width: 100%"
                  :header-cell-style="{ background: '#EEEEEE' }"
                  :row-class-name="tableRowClassName"
                  :data="tableData"
                  v-loading="loading"
                  row-key="pkId"
                  height="550px"
                  lazy
                  ref="table1"
                  :load="load"
                  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          >
          <el-table-column type="selection"
                           width="55"> </el-table-column>

          <el-table-column align="left"
                           prop="name"
                           :label="'地区名称'"
                           width="200">
          </el-table-column>
          <el-table-column align="center"
                           prop="code"
                           :label="'地区编号'">
          </el-table-column>
          <el-table-column align="center"
                           prop="enableState"
                           label="启用状态">
            <template slot-scope="scope">
              <div>{{ scope.row.enableState==0?'启用':'停用' }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="time"
                           :label="'操作'"
                           fixed="right"
                           width="240">
            <template slot-scope="scope">
              <el-button @click.native.prevent="update(scope.row, tableData)"
                         class="button-s"
                         type="text"
                         size="small"
                         style="color: #6962f6"
                         v-has-buttons="['DivisionUpdate']">
                {{ '修改' }}
              </el-button>
              <el-button @click.native.prevent="addRow(scope.row, tableData)"
                         class="button-s"
                         type="text"
                         size="small"
                         style="color: #3181e5"
                         v-has-buttons="['DivisionAdd']">
                {{'新增'}}
              </el-button>
              <el-button @click.native.prevent="deleteRow(scope.row, tableData)"
                         class="button-s"
                         type="text"
                         size="small"
                         style="color: #c73030"
                         v-has-buttons="['DivisionDelete']">
                {{ '删除' }}
              </el-button>
            </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" />
    <el-dialog :title="updateTitle"
               :visible.sync="updateShow"
               width="36%"
               center
               :before-close="handleClose">
      <el-form ref="form"
               :rules="rules"
               :model="form"
               label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="'地区名称'"
                          prop="name">
              <el-input clearable
                        v-model="form.name"
                        :placeholder="'请输入地区名称'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="'地区编号'"
                          prop="code">
              <el-input clearable
                        v-model="form.code"
                        :placeholder="'请输入地区编号'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="启用状态"
                          prop="enableState">
              <el-select v-model="form.enableState"
                         clearable>
                <el-option v-for="item,index in statusList"
                           :key="index"
                           :label="item.name"
                           :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer"
            style="display: inline-block; padding-top: 100px"
            class="dialog-footer">
        <el-button @click="handleClose"
                   class="cancel">{{'取消'}}</el-button>
        <el-button class="submit"
                   type="primary"
                   @click="onSubmit('form')">{{'确认'}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

  <script>
import topBar from '@/components/topBar'
import { handleTree } from '@/utils/ruoyi'

import {
  getarealist,
  getareaLevellist,
  deletManageArea,
  getareaDetailList,
  saveArea,
  updateArea,
} from '@/api/division'
export default {
  name: 'Xzph',
  components: {
    topBar,
  },
  data() {
    return {
      moren: 'xzph',
      topList: [
        {
          name: '行政区划',
          path: 'xzph',
        },
      ],
      tableData: [],
      loading:false,
      multipleSelection: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        code: '',
        name: '',
      },
      maps: new Map(),
      updateShow: false,
      addOrEdit: '', //添加还是修改 true添加 false修改
      updateTitle: '',
      form: {
        name: '',
        code: '',
        enableState: 0,
      },
      statusList: [
        { name: '启用', id: 0 },
        { name: '停用', id: 1 },
      ],
      rules: {
        name: [
          { required: true, message: '请输入地区名称', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入地区编号', trigger: 'blur' },
        ],
        enableState: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
      },
      nowRow: {}, //暂存修改的row
    }
  },
  created() {
    this.getarealist()
  },
  methods: {
    exports() {
      this.download(
        '/system/manage/area/export',
        Object.assign({}, this.queryParams),
        `${'行政区划'}-${new Date().getTime()}.xlsx`
      )
    },
    //保存
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addOrEdit == 1) {
            saveArea(this.form).then((res) => {
              if (res.code == 200) {
                this.updateShow = false
                this.$message({
                  message: res.msg,
                  type: 'success',
                })
                this.getarealist()
                this.addOrEdit = ''
              }
            })
          } else if (this.addOrEdit == 2) {
            updateArea(this.form).then((res) => {
              if (res.code == 200) {
                this.updateShow = false
                this.$message({
                  message: res.msg,
                  type: 'success',
                })
                this.getarealist()
                this.addOrEdit = ''
                // if (this.nowRow.pId) {
                //   //区分子父节点 父节点1 子节点空
                const { tree, treeNode, resolve } = this.maps.get(
                  this.nowRow.parent
                )
                //根据父级id取出对应的节点数据
                //   //将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                //   this.$set(
                //     this.$refs.table1.store.states.lazyTreeNodeMap,
                //     tree.parent,
                //     []
                //   )
                //   //实现数据的重新加载
                this.load(tree, treeNode, resolve)
                // } else {
                //   //pId为0时重新加载表格
                //   this.getarealist()
                //   this.addOrEdit = ''
                // }
              }
            })
          } else if (this.addOrEdit == 3) {
            saveArea(this.form).then((res) => {
              if (res.code == 200) {
                this.updateShow = false
                this.$message({
                  message: res.msg,
                  type: 'success',
                })
                this.getarealist()
                this.addOrEdit = ''
                // if (this.nowRow.pId) {
                //   //区分子父节点 父节点1 子节点空
                //   const { tree, treeNode, resolve } = this.maps.get(
                //     this.nowRow.parent
                //   ) //根据父级id取出对应的节点数据
                //   //将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                //   this.$set(
                //     this.$refs.table1.store.states.lazyTreeNodeMap,
                //     tree.parent,
                //     []
                //   )
                //   //实现数据的重新加载
                //   this.load(tree, treeNode, resolve)
                // } else {
                //   //pId为0时重新加载表格
                //   this.getarealist()
                //   this.addOrEdit = ''
                // }
              }
            })
          }
        }
      })
    },
    //修改
    update(row) {
      this.updateShow = true
      this.updateTitle = '修改'
      this.addOrEdit = 2
      getareaDetailList({ pkId: row.pkId }).then((res) => {
        this.form = res.data
      })
      this.nowRow = row
    },
    //表单内行添加
    addRow(row) {
      console.log('🌈', row)
      this.updateShow = true
      this.updateTitle = '添加'
      this.addOrEdit = 3
      // getareaDetailList({ pkId: row.pkId }).then((res) => {
      //   this.form = res.data;
      // });
      this.form.parent = row.pkId
      this.nowRow = row
      // this.$refs['form'].clearValidate()
      // this.$refs['form'].resetFields()
    },
    //添加
    adddate() {
      this.updateShow = true
      this.updateTitle = '添加'
      this.addOrEdit = 1
      // this.$refs['form'].clearValidate()
      // this.$refs['form'].resetFields()
    },
    //重置
    reChongzhi() {
      this.queryParams.name = ''
      this.queryParams.code = ''
    },
    handleClose() {
      this.updateShow = false
      // this.$refs['form'].clearValidate()
      // this.$refs['form'].resetFields()
    },
    //删除
    deleteRow(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletManageArea(row.pkId).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            //pId为0时重新加载表格
            this.getarealist()
          } else {
            this.$message({
              message: res.msg,
              type: 'warning',
            })
          }
        })
      })
    },

    //懒加载
    load(tree, treeNode, resolve) {
      this.maps.set(tree.pkId, { tree, treeNode, resolve })
      getareaLevellist({ parent: tree.pkId }).then((res) => {
        res.data.forEach((item) => {
          item.pId = 1
          if (item.levelCount > 0) {
            item.hasChildren = true
          } else {
            item.hasChildren = false
          }
        })
        resolve(res.data)
      })
    },
    //获取全部地区列表
    getarealist() {
      this.loading = true
      getarealist(this.queryParams).then((res) => {
        res.rows.forEach((item) => {
          item.pId = 1
          if (item.levelCount > 0) {
            item.hasChildren = true
          } else {
            item.hasChildren = false
          }
        })
        // this.tableData = res.rows
        this.tableData = handleTree(res.rows, 'pkId')
        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>
::v-deep .el-form-item {
  margin-bottom: 15px;
}
.button-s {
  padding: 3px 0;
}
::v-deep .el-input__inner {
  height: 32px;
  line-height: 32px;
}
//::v-deep .el-table__expand-icon{
//  position: absolute;
//  right: 5px;
//}
::v-deep .el-dialog__title {
  font-weight: bold;
}
::v-deep .el-row {
  margin-top: 0;
}
.cancel {
  width: 209px;
  height: 48px;
  background: #cccccc;
  border-radius: 5px 5px 5px 5px;
  color: #fff;
  border-color: #fff;
}
.submit {
  width: 209px;
  height: 48px;
  background: #48b2fd;
  border-radius: 5px 5px 5px 5px;
  color: #fff;
  margin-left: 40px;
  border-color: #48b2fd;
}
::v-deep .el-form-item__label {
  color: #333;
  font-weight: inherit;
}
.thebtn1 {
  background: #3181e5;
  color: #ffffff;
  border-radius: 4px;
  width: 68px;
  height: 32px;
}
.thebtn2 {
  background: #ffad41;
  color: #ffffff;
  border-radius: 4px;
  width: 68px;
  height: 32px;
}
.thebtn3 {
  background: #ff6723;
  color: #ffffff;
  border-radius: 4px;
}
::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 0px 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);
    //overflow: hidden;;
    .maintop {
      display: flex;
      padding: 10px 0;
      justify-content: space-between;
      align-items: center;

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