<template>
  <div class="app-container">
       <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">地块管理</h1>
      <br />

     <!-- 搜索工作栏 -->
      <RecordForm
      ref="searchForm"
      :searchFormParam="{queryParams, dataSource}"
      :showSearch.sync="showSearch"
      @handleQuery="handleQuery"
      @resetQuery="resetQuery"
      @selectChage="selectChage"
      ></RecordForm>
    </div>

    <div class="app-container-list main-bgcolor main-radius">
      <!-- 操作工具栏 -->
      <h1>地块列表</h1>

      <el-button
        style="float: right; margin-bottom: 10px"
        type="primary"
        :loading="exportLoading"
        @click="handleAdd"
        v-hasPermi="['product:land-info:create']"
        >添加地块</el-button>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地块名称" align="center" prop="landName" />
        <el-table-column label="地块编码" align="center" prop="landId" />
        <el-table-column label="类型" align="center" prop="infoTypeName" >
        </el-table-column>
        <el-table-column label="所属商户" align="center" prop="belongBusinessName" />
        <el-table-column label="面积" align="center" prop="size" />
        <el-table-column label="状态" align="center" prop="infoStateName" >
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="操作" fixed="right" class-name="small-padding fixed-width" width="150">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['product:land-info:update']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['product:land-info:delete']">删除</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" class="goods-verify" :visible.sync="open" width="530px" v-dialogDrag append-to-body>
      <el-form ref="form" :rules="rules" label-position="top" :model="form"  label-width="80px">
        <el-form-item label="所属商户" prop="belongBusinessId">
          <el-select ref="businessName" @change="handchangeBusiness" v-model="form.belongBusinessId" placeholder="请选择所属商户">
            <el-option v-for="item in businessNameList" :key="item.id" :label="item.businessName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="地块名称" prop="landName">
          <el-input v-model="form.landName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="地块类型" prop="landType">
          <el-select v-model="form.landType" placeholder="请先选择所属商户">
            <el-option :key="item.id" v-for="item in landTypeList" :label="item.landTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
         <el-select v-model="form.state" placeholder="请先选择所属商户">
            <el-option :key="item.id" v-for="item in stateList" :label="item.landStateName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="面积" prop="size">
          <el-input placeholder="请输入" v-model="form.size" type="number" min="0" step="0.01" @change="changeSize">
              <template slot="append">亩</template>
            </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" class="w150" v-model="form.remarks" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createLandInfo, updateLandInfo, deleteLandInfo, getLandInfo, getLandInfoPage, exportLandInfoExcel } from "@/api/product/landInfo";
import { getBusinessNameList } from '@/api/basic/businessInfo';
import { getByBusinessInfoId } from '@/api/product/landInfoType';
import { getBusinessInfoByListLandBlockState } from '@/api/product/landBlockState';

import RecordForm from '@/components/Customer/SearchForm'
import EmptyTable from '@/components/EmptyTable'

export default {
  name: "LandInfo",
  components: {
    RecordForm,
    EmptyTable,
  },
  data() {
    return {
      options: [{
        value: 0,
        label: '修整'
      },{
        value: 1,
        label: '种植'
      }],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 农事土地信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        landName: null,
        landId: null,
        size: null,
        state: null,
        remarks: null,
        landType: null,
        belongBusinessId: null,
        belongBusinessName: null,
        createTime: [],
        status: null,
      },
       dataSource: [
        {
          key: 'landName',
          itemType: 'input',
          label: '地块名称',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'landId',
          itemType: 'input',
          label: '地块编码',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'belongBusinessName',
          itemType: 'select',
          label: '所属商户',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
          options:[],
          isNet: true,
        },
        {
          key: 'state',
          itemType: 'select',
          label: '状态',
          placeholder: '请先选择所属商户',
          onEnterKeyUp: this.handleQuery,
          options: [],
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "blur" }],
        landName: [{ required: true, message: "地块名称不能为空", trigger: "blur" }],
        landType: [{ required: true, message: "地块类型不能为空", trigger: "blur" }],
        landId: [{ required: true, message: "地块编码不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },
      // 所属商户列表
      businessNameList: [],
      landTypeList:[],
      stateList: [],
    };
  },
  created() {
    this.getList();
    this.initDate();
  },
  methods: {
    async initDate(){
      // 商户列表
      let res = await getBusinessNameList();
      this.businessNameList = res.data;
      res.data.map(item=>{
        item.label = item.businessName;
        item.value = item.businessName;
      });
      this.dataSource[2].options = res.data;
    },
    //获取所有商户昵称
    handchangeBusiness(e){
      this.$nextTick(async ()=>{
         this.form.belongBusinessName = this.$refs.businessName.selected.label;
         let res = await getByBusinessInfoId({id: e});
         console.log("获取商户昵称对应的地块类型列表",res);
         if(res.data) this.landTypeList = res.data;
         if(!res.data) this.landTypeList = [];

         let resState = await getBusinessInfoByListLandBlockState({id: e});
         console.log("获取商户对应的地块状态列表",resState);
         if(res.data) this.stateList = resState.data;
         if(!res.data) this.stateList = [];
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getLandInfoPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        landName: undefined,
        landId: undefined,
        size: undefined,
        state: undefined,
        remarks: undefined,
        landType: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dataSource[3].options = []
      this.resetForm("queryForm","searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加地块";
      this.landTypeList = [];
      this.stateList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getLandInfo(id).then(async response => {
        this.form = response.data;
        this.form.state = Number( this.form.state );
        this.open = true;
        this.title = "修改农事土地信息";

        let res = await getByBusinessInfoId({id: response.data.belongBusinessId});
        console.log("获取商户昵称对应的地块类型列表",res);
        if(res.data) this.landTypeList = res.data;
        if(!res.data) this.landTypeList = [];

        let resState = await getBusinessInfoByListLandBlockState({id: response.data.belongBusinessId});
        console.log("获取商户对应的地块状态列表",resState);
        if(res.data) this.stateList = resState.data;
        if(!res.data) this.stateList = [];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateLandInfo(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createLandInfo(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除农事土地信息编号为"' + id + '"的数据项?').then(function() {
          return deleteLandInfo(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有农事土地信息数据项?').then(() => {
          this.exportLoading = true;
          return exportLandInfoExcel(params);
        }).then(response => {
          this.$download.excel(response, '农事土地信息.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },

    selectChage({ value, type, book }) {
      if (type != 'state') {
        this.queryParams.state = ''
      }
      if (!book) {
        return
      }
      if(value == null || value == ''){
        this.dataSource[3].options = []
        return
      }

      let businessInfo = this.businessNameList.find(item=>item.businessName == value);
      getBusinessInfoByListLandBlockState({
        id: businessInfo.id,
      }).then((res) => {
        this.$nextTick(() => {
          this.dataSource[3].options = res.data.map((el) => {
            let obj = {
              label: el.landStateName,
              value: el.id,
              key: el.id,
            }
            return obj
          })
        })
      })
    },
    
    // 改变面积
    changeSize(e){
      this.form.size = Number(e).toFixed(2);
    },

  }
};
</script>
<style scoped lang="scss">
  .goods-verify{
    .el-select{
      width: 100%;
    }
    .el-date-editor{
      width: 90%;
    }
  }

  .hide {
    ::v-deep .el-upload--picture-card {
      display: none !important;
    }
  }

  .verifyFileUpload{
    ::v-deep .el-icon-document{
      white-space:nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      width: 240px;
    }
  }

  .table-column{
    display: flex;
    align-items: center;
    justify-content: center;
    .dian{
      width: 5px;
      height: 5px;
      border-radius: 100%;
      background-color: rgb(217, 217, 217);
      display: inline-block;
    }
    .dian-active{
      background-color: rgb(82, 196, 26);
    }
    .column-content{
      display: inline-block;
      padding-left: 6px;
    }
  }


</style>
