<template>
  <el-row class="el-row-container" style="height: 100%" v-loading="loading">
    <el-col :span="4" style="height: 100%; padding-bottom: 32px">
      <el-card style="margin: 16px; height: 100%; overflow-y: auto">
        <data-report-left
          @setCurrentData="setCurrentData"
          :treeData="treeData"
        ></data-report-left>
      </el-card>
    </el-col>
    <el-col :span="20" style="padding: 16px 16px 16px 0; height: 100%">
      <el-card style="height: 100%; overflow-y: auto">
        <el-col :span="24" class="elrow-main__col-top">
          <div style="display: flex">
            <el-input
              v-model="farmerName"
              style="width: 250px"
              placeholder="请输入姓名/电话"
              @keyup.enter.native="handleSearch"
              clearable
            />
            <el-button
              type="primary"
              size="small"
              style="margin: 0 16px"
              @click="handleSearch"
              >查询</el-button
            >
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleUploadError"
              name="file"
              :headers="headers"
              :data="{ areaId: this.currentClickId }"
              :before-upload="beforeAvatarUpload"
              ><el-button
                size="small"
                type="primary"
                style="height: 36px; margin-right: 16px"
                v-hasPermi="['wpr:farmer:import']"
                >导入</el-button
              >
            </el-upload>
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-download"
              @click="downloadExcel()"
              v-hasPermi="['wpr:farmer:template:upload']"
              >下载模板</el-button
            >
          </div>
          <div class="top-left">
            <el-button
              type="primary"
              size="small"
              @click="addAssociation"
              v-hasPermi="['wpr:farmer:add']"
              >新增农户
            </el-button>
          </div>
        </el-col>
        <el-col :span="24" class="elrow-main__col-bottom">
          <b-table
            ref="tableRef"
            :args="{ 'highlight-current-row': true }"
            :data="loadData"
            :columns="columns"
            isShowIndex
          >
            <template #status="scope">
              <span
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <span class="status"></span>
                {{ scope.row.name }}
              </span>
            </template>
            <template #operate="scope">
              <el-link
                size="small"
                :underline="false"
                type="primary"
                style="margin-right: 10px"
                @click="irrigationShowHistory(scope.row)"
                v-hasPermi="['wpr:farmer:Irrigation:records']"
                >灌溉记录</el-link
              >
              <el-link
                size="small"
                :underline="false"
                type="primary"
                style="margin-right: 10px"
                v-hasPermi="['wpr:farmer:edit']"
                @click="editFarmerHandler(scope.row)"
                >修改</el-link
              >
              <el-link
                size="small"
                :underline="false"
                type="primary"
                style="margin-right: 10px"
                v-hasPermi="['wpr:farmer:info']"
                @click="showDetails(scope.row)"
                >详情</el-link
              >
              <el-link
                slot="reference"
                size="small"
                :underline="false"
                type="danger"
                style="margin-right: 10px"
                v-hasPermi="['wpr:farmer:delete']"
                @click="deleteRow(scope.row)"
                >删除</el-link
              >
            </template>
          </b-table>
        </el-col>
      </el-card>
    </el-col>
  <added-farmers
    :visible.sync="associationManageShow"
    :treeData="treeDatas"
    :editFarmerData="editFarmerData"
    :isEdit="isEdit"
    :currentClickId="currentClickId"
    @refresh="handleSearch"
    @closeHandler="closeHandler"
  />
  <farmer-management 
    :visible.sync="farmerManageShow"
    :detailsData="detailsData"
  />
  <irrigation-record
    :visible.sync="irrigationShow"
    :irrigationDetail="irrigationDetail"
  />
  </el-row>
</template>

<script>
import { getToken } from '@/utils/auth';
import { Message } from 'element-ui';
import { getTree } from '@/api/tree.js';
import { getWaterrightList } from '@/api/waterright/index.js';
import {
  getFarmerList,
  deleteFarmer,
  getFarmerDetail
} from '@/api/farmer/list.js';
import BTable from '@/components/Table/index.vue';
import DataReportLeft from '@/components/DataReportLeft/index.vue';
import AddedFarmers from './components/addedFarmers.vue';
import FarmerManagement from './components/farmerManagement.vue';
import IrrigationRecord from './components/IrrigationRecord.vue';
import { assign, omit } from 'lodash-es';

export default {
  name: 'peasantHouseholdManage',
  components: {
    BTable,
    DataReportLeft,
    AddedFarmers,
    FarmerManagement,
    IrrigationRecord
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/wpr/farmer/import', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      currentData: {},
      visibles: false,
      farmerName: '',
      detailsData: {},
      treeData: [],
      treeDatas: [],
      currentClick: {},
      irrigationDetail: {},
      isEdit: false,
      loading: false,
      associationManageShow: false,
      farmerManageShow: false,
      irrigationShow: false,
      editFarmerData: {},
      farmerId: '',
      requestData: {},
      currentClickId: '',
      columns: [
        {
          label: '农户姓名',
          prop: 'farmerName',
          customRender: '',
          align: 'center'
        },
        {
          label: '农户身份证',
          prop: 'farmerIdcard',
          width: 200,
          customRender: '',
          align: 'center',
        },
        {
          label: '联系电话',
          prop: 'farmerPhone',
          customRender: '',
          align: 'center'
        },
        {
          label: '种植面积（亩）',
          prop: 'farmerAreasize',
          customRender: '',
          align: 'center'
        },
        {
          label: '水权数量（m³）',
          prop: 'farmerWramount',
          customRender: '',
          align: 'center'
        },
        {
          label: '剩余水权（m³）',
          prop: 'farmerWrbalance',
          customRender: '',
          align: 'center'
        },
        {
          label: '操作',
          customRender: 'operate',
          width: 200,
          align: 'center'
        }
      ]
    };
  },
  methods: {
    closeHandler() {
      this.editFarmerData = {}
    },
    handleAvatarSuccess(res, file) {
      if (res.code !== '000000') {
        Message.error(res?.msg);
        return;
      } else {
        Message.success('导入成功');
      }
    },
    handleUploadError() {
      Message.error('图片插入失败');
    },
    beforeAvatarUpload() {
      if (this.currentData?.children?.length > 0) { 
        Message.warning('请选择最小行政区块')
        return false
      }
      this.requestData = {
        areaId: this.currentClickId
      };
    },
    downloadExcel() {
      const href =
        process.env.NODE_ENV === 'production'
          ? '../../../wpr/static/template.xlsx'
          : '../../../static/template.xlsx';
      let a = document.createElement('a');
      a.href = href;
      a.download = '农户信息统计表.xlsx';
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    editFarmerHandler(row) {
      this.associationManageShow = true;
      this.isEdit = true;
      this.editFarmerData = row;
    },
    async getDetail(farmerId) {
      const res = await getFarmerDetail({
        farmerId
      });
      this.detailsData = res?.data;
    },
    async getWaterrighTreetList(currentClickId) {
      const date = new Date();
      const waterrightYear = date.getFullYear();
      const res = await getWaterrightList({
        waterrightYear
      });
      this.treeDatas = res?.data ?? [];
    },
    async loadData(parameter) {
      if (!this.currentClickId) {
        const treeList = this.$store.state.tree.treeList;
        let res = [];
        if (treeList.code === '000000') {
          res = treeList;
        } else {
          res = await getTree();
          this.$store.dispatch('tree/setTree', res);
        }
        this.treeData = res?.data
        let tflag = true
        this.treeData.forEach(t => {
          if (t?.cusareaName == '全部') {
            tflag = false
          }
        })
        if (tflag) {
          this.treeData.unshift({
            id: '',
            cusareaId: '',
            cusareaName: '全部'
          })
        }
        this.currentClick = res?.data[0]
        this.currentClickId = this.currentClick?.cusareaId
        this.currentData = this.currentClick
        this.getWaterrighTreetList(this.currentClickId)
      }
      const params = {
        farmerName: this.farmerName,
        areaId: this.currentClickId
      };
      const payload = omit(assign({}, parameter, params), []);
      return getFarmerList(payload);
    },
    setCurrentData(areaId, data) {
      this.currentData = data
      this.currentClickId = areaId
      this.$refs.tableRef.refresh(false);
    },
    irrigationShowHistory(row) {
      this.irrigationDetail = row;
      this.irrigationShow = true;
    },
    // 详情
    showDetails(row) {
      this.farmerManageShow = true;
      this.farmerId = row.farmerId;
      this.getDetail(row.farmerId);
    },
    addAssociation() {
      this.isEdit = false;
      this.editFarmerData = {};
      this.associationManageShow = true;
    },
    handleSearch() {
      this.$refs.tableRef.refresh(true);
    },
    handlerChange() {
      this.$refs.tableRef.refresh(false);
    },
    deleteRow(row) {
      this.$modal.confirm(`是否确认删除农户${row.farmerName}`).then(() => {
        deleteFarmer({
          farmerIds: row.farmerId
        }).then(() => {
          Message({ message: '删除成功', type: 'success' });
          this.handlerChange();
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-row-container {
  height: 100%;
}
.elrow-main__col-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  .top-left {
    height: 100%;
    display: flex;
    align-items: center;
    i {
      background-color: #40d5ec;
      height: 45%;
      width: 5px;
      margin-right: 5px;
    }
  }
}
.status {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: red;
  margin-right: 5px;
}
</style>
