<template>
  <section class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      v-model:search="searchCondition"
      class="custon_create_land_"
      :data="data"
      :option="option"
      :before-close="handleCloseFrom"
      :table-loading="loading"
      @refresh-change="getList()"
      @current-change="getList()"
      @size-change="handleSizeChange"
      @search-reset="
        () => {
          resetLandType();
          getList(1);
        }
      "
      @search-change="
        (form, done) => {
          getList(1);
          done();
        }
      "
      @row-save="handleRowSave"
      @row-update="handleRowUpdate"
    >
      <template #landTransfer="{ row }">
        {{ row.landTransfer == '1' ? '是' : '否' }}
      </template>
      <template #isUpload="{ row }">
        {{ row.isUpload != '1' ? '是' : '否' }}
      </template>
      <template #menu-left>
        <el-button type="success" icon="download" @click="handleExport">导出</el-button>
        <el-button type="success" icon="upload" @click="onUpload">导入</el-button>
      </template>
      <template #area-form="{ type }">
        <section v-show="type != 'view'" class="area_form_">
          <el-input-number v-model="landArea" :precision="2" :step="1" :min="1" controls-position="right"></el-input-number>
          <el-select v-model="unitValue">
            <el-option v-for="item in unitOptions" :key="'unitOptions_' + item.value" :label="item.label" :value="item.label" />
          </el-select>
        </section>
        <section v-show="type == 'view'">
          {{ landArea + unitValue }}
        </section>
      </template>
      <template #propertyCertificateUrl-form="{ type }">
        <Attrs v-model:attrs="attrs" :type="type" />
      </template>
      <template #landCertificateUrl-form="{ type }">
        <Attrs v-model:attrs="landOwnerAttrs" :type="type" />
      </template>
      <template #coordinate-form>
        <avue-input-map v-model="local" :params="params" placeholder="请选择位置"></avue-input-map>
      </template>
      <template #landUrl-form="{ type }">
        <Attrs v-model:attrs="landAttrs" :type="type" />
      </template>

      <template #menu="scope">
        <custom-table-operate :actions="option.actions" :data="scope" />
      </template>
    </avue-crud>
    <custom-import-excel
      ref="importExcelRef"
      :template-url="getAssetsFile('template/土地模版表.xlsx')"
      @on-download="onDownloadExcel"
      @on-confirm="onUploadExcel"
    />
  </section>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { CRUD_OPTIONS } from '@/config';
import { useUserStore } from '@/store/modules/user';
import { getLandsList, exportLands, delLand, saveLand, importLands, editLand } from '@/apis/land.js';
import { getRegion } from '@/apis';
import { ElMessage } from 'element-plus';
import useLandHook from './useLandHook';
import Attrs from './common/Attrs.vue';
import { getAssetsFile, downloadFile } from '@/utils';
import { useApp } from '@/hooks';

const app = useApp();
const { loadFinish, resetLandType, searchCondition, unitOptions, unitValue, landTreeDic } = useLandHook();
const { VITE_APP_BASE_API } = import.meta.env;
const UserStore = useUserStore();

watch(
  () => loadFinish.value,
  () => {
    if (loadFinish.value == 2) {
      getList();
      handleGetRegion();
    }
  }
);

const params = ref({
  zoom: 10,
});
const local_ = ref([102.833669, 24.88149, '昆明市']);
const local = ref(JSON.parse(JSON.stringify(local_.value)));
const landArea = ref(1);

/* --------------- data --------------- */
// #region
const loading = ref(false);
const crudRef = ref();
const pageData = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const data = ref([]);
const option = reactive({
  ...CRUD_OPTIONS,
  menuWidth: 120,
  selection: false,
  column: [
    {
      hide: true,
      label: '用地分类',
      prop: 'landType',
      search: true,
      type: 'cascader',
      dicData: landTreeDic,
      clearable: false,
      value: [],
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '地块名称',
      prop: 'landName',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 200,
    },
    {
      label: '地址',
      prop: 'address',
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 300,
    },
    {
      label: '经营主体',
      prop: 'owner',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 100,
    },
    {
      label: '所属网格',
      prop: 'gridName',
      // type: 'select',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '农用地分类',
      prop: 'landClassificationType',
      select: 'select',
      dicData: landTreeDic,
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 300,
    },
    {
      label: '面积',
      prop: 'area',
      addDisplay: false,
      display: false,
      editDisplay: false,
      render: ({ row }) => {
        let s = '';
        if (row.area && row.landUnit) {
          s = row.area + row.landUnit;
        }
        return s;
      },
    },
    {
      label: '坐标',
      prop: 'coordinate',
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 300,
    },
    {
      label: '是否流转土地',
      prop: 'landTransfer',
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 140,
    },
    {
      label: '产权编号',
      prop: 'landCode',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '土壤类型',
      prop: 'soilTypeName',
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: '是否上传附件',
      prop: 'isUpload',
      addDisplay: false,
      display: false,
      editDisplay: false,
      width: 140,
    },
  ],
  group: [
    {
      label: '用户信息',
      prop: 'baseGroup',
      column: [
        {
          label: '土地名称',
          prop: 'landName',
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '所属网格',
          prop: 'gridId',
          type: 'select',
          dicUrl: `${VITE_APP_BASE_API}/land-resource/gridManage/page`,
          dicQuery: {
            current: 1,
            size: 9999,
          },
          props: {
            value: 'id',
            label: 'gridName',
          },
          dicHeaders: {
            authorization: UserStore.token,
          },
          dicFormatter: handleGetGrid,
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
          change: handleChangeGrid,
        },
        {
          label: '用地分类',
          prop: 'landTypeId',
          type: 'cascader',
          dicData: landTreeDic,
          viewDisplay: false,
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '用地分类',
          prop: 'landClassificationType',
          addDisplay: false,
          editDisplay: false,
        },
        {
          label: '位置',
          prop: '_villageCode',
          type: 'cascader',
          props: {
            label: 'areaName',
            value: 'areaCode',
            children: 'areaChildVOS',
          },
          rules: [
            {
              required: true,
              message: '请选择',
              trigger: 'blur',
            },
          ],
          viewDisplay: false,
        },
        {
          hide: true,
          label: '位置',
          prop: 'address',
          addDisplay: false,
          editDisplay: false,
        },
        {
          label: '是否土地流转',
          prop: 'isTransfer',
          type: 'select',
          viewDisplay: false,
          dicData: [
            {
              label: '是',
              value: '0',
            },
            {
              label: '否',
              value: '1',
            },
          ],
        },
        {
          label: '是否土地流转',
          prop: 'isTransferView',
          addDisplay: false,
          editDisplay: false,
        },
        {
          label: '面积',
          prop: 'area',
        },
        {
          label: '经营主体',
          prop: 'owner',
        },
        {
          label: '土壤类型',
          prop: 'soilTypeId',
          type: 'select',
          viewDisplay: false,
          dicUrl: `${VITE_APP_BASE_API}/land-resource/baseInfo/soilTypePage`,
          dicQuery: {
            current: 1,
            size: 9999,
          },
          dicHeaders: {
            authorization: UserStore.token,
          },
          dicFormatter: (res) => res.data.records ?? [],
          props: {
            value: 'id',
            label: 'soilType',
          },
        },
      ],
    },
    {
      label: '土地产权信息',
      prop: 'baseGroup',
      column: [
        {
          label: '经营主体姓名',
          prop: 'propertyName',
        },
        {
          label: '经营主体联系电话',
          prop: 'propertyPhone',
        },
        {
          label: '产权编号',
          prop: 'landCode',
        },
        {
          label: '产权证书',
          prop: 'propertyCertificateUrl',
        },
      ],
    },
    {
      label: '土地使用权信息',
      prop: 'baseGroup',
      column: [
        {
          label: '联系人',
          prop: 'landUseName',
        },
        {
          label: '联系电话',
          prop: 'landUsePhone',
        },
        {
          label: '用地性质',
          prop: 'nature',
        },
        {
          label: '证书',
          prop: 'landCertificateUrl',
        },
      ],
    },
    {
      label: '土地使用权信息',
      prop: 'baseGroup',
      column: [
        {
          label: '地理位置',
          prop: 'coordinate',
          viewDisplay: false,
        },
        {
          label: '地理位置',
          prop: 'coordinateView',
          addDisplay: false,
        },
        {
          label: '图片',
          prop: 'landUrl',
        },
      ],
    },
  ],
  actions: [
    {
      name: '查看',
      icon: 'view',
      event: ({ row }) => handleView(row),
    },
    {
      name: '编辑',
      icon: 'edit',
      event: ({ row }) => rowEdit(row),
    },
    {
      type: 'danger',
      name: '删除',
      icon: 'delete',
      event: ({ row }) => handleDelete(row.id),
    },
  ],
});
const attrs = ref([]);
const landOwnerAttrs = ref([]);
const landAttrs = ref([]);
const rowData = ref([]);
const importExcelRef = ref();
const regionData = ref([]);
// #endregion

/* --------------- methods --------------- */
// #region

async function getList(reset = 1) {
  reset == 1 && (pageData.value.currentPage = 1);
  loading.value = true;
  let params = Object.assign(
    {},
    {
      current: pageData.value.currentPage,
      size: pageData.value.pageSize,
      ...searchCondition.value,
    }
  );
  params.landType = searchCondition.value.landType[searchCondition.value.landType.length - 1];
  let res = await getLandsList(params);
  loading.value = false;
  if (res.code == 200) {
    const { total, records } = res.data;
    data.value = records;
    data.value.forEach((v) => {
      v.isTransfer = v.landTransfer || '1';
      v.isTransferView = v.landTransfer == '1' ? '否' : '是';
      v.coordinateView = v.coordinate;
      v.soilTypeName = v.soilType;
      v.soilTypeId = v.soilId;
      v._villageCode = typeof v.villageCode == 'string' ? [v.villageCode] : v.villageCode;
      v.landTypeId = [v.pid, v.landType];
    });
    pageData.value.total = total;
  }
}
function handleGetGrid(res) {
  return res?.data?.records ?? [];
}
function handleChangeGrid(val) {
  val.item && filterArea(val.item.townCode);
}
function filterArea(id) {
  option.group[0].column[4].dicData = regionData.value.find((v) => v.areaCode == id)?.areaChildVOS ?? [];
}
async function handleGetRegion() {
  let res = await getRegion();
  if (res.code == 200) {
    regionData.value = res?.data?.[0].areaChildVOS?.[0].areaChildVOS?.[0].areaChildVOS ?? [];
  }
}
function handleSizeChange(val) {
  pageData.value.pageSize = val;
  getList();
}
async function handleExport() {
  let res = await exportLands({
    landType: searchCondition.value.landType[searchCondition.value.landType.length - 1],
  });
  if (res) {
    let a = document.createElement('a');
    a.download = 'test.xlsx';
    let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    let link = window.URL.createObjectURL(blob);
    a.href = link;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(link);
  }
}
function handleDelete(id) {
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      delLand(id)
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            getList();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
}
function handleView(obj) {
  handleOtherInfo(obj);
  rowData.value = obj;
  crudRef.value.rowView(obj);
}
function handleCloseFrom(done) {
  landOwnerAttrs.value = [];
  attrs.value = [];
  landAttrs.value = [];
  landArea.value = 1;
  unitValue.value = unitOptions[0].label || '';
  local.value = JSON.parse(JSON.stringify(local_.value));
  done();
}
function handleData(val) {
  let data = JSON.parse(JSON.stringify(val));
  data.isDraftsSave = 0;
  data.landType = searchCondition.value.landType[searchCondition.value.landType.length - 1];
  let urls = [];
  let landOwnerUrls = [];
  let landUrls = [];
  if (attrs.value.length) {
    attrs.value.forEach((item) => urls.push(item.url));
  }
  if (landOwnerAttrs.value.length) {
    landOwnerAttrs.value.forEach((item) => landOwnerUrls.push(item.url));
  }
  if (landAttrs.value.length) {
    landAttrs.value.forEach((item) => landUrls.push(item.url));
  }
  data.area = landArea.value;
  data.landUnit = unitValue.value;
  data.propertyCertificateUrl = urls.join();
  data.landCertificateUrl = landOwnerUrls.join();
  data.landUrl = landUrls.join();
  data.villageCode = data._villageCode[0];
  data.landTypeId = data.landTypeId[data.landTypeId.length - 1];
  data.soilType = data.soilTypeId;
  if (local.value.length != 0) {
    data.coordinate = `${local.value[0]}E,${local.value[1]}N`;
  }
  delete data.address;
  delete data.provinceCode;
  delete data.cityCode;
  delete data.county;
  delete data.townCode;
  return data;
}
async function handleRowSave(val, done, loading) {
  let data = handleData(val);
  const res = await saveLand(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getList();
    attrs.value = [];
    landOwnerAttrs.value = [];
    done();
  }
}
async function handleRowUpdate(form, index, done, loading) {
  let data = handleData(form);
  let res = await editLand(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('编辑成功');
    done();
  }
}

async function rowEdit(row) {
  handleOtherInfo(row);
  filterArea(row.townCode);
  crudRef.value.rowEdit(row);
}
function handleOtherInfo(obj) {
  landArea.value = obj.area;
  unitValue.value = obj.landUnit;
  if (obj.propertyCertificateUrl) {
    attrs.value = obj.propertyCertificateUrl.split(',').map((v, i) => {
      return {
        name: `产权附件_${i}`,
        url: v,
        uid: 'id_' + Date.now(),
      };
    });
  }
  if (obj.landCertificateUrl) {
    landOwnerAttrs.value = obj.landCertificateUrl.split(',').map((v, i) => {
      return {
        name: `使用信息附件_${i}`,
        url: v,
        uid: 'id_' + Date.now(),
      };
    });
  }
  if (obj.landUrl) {
    landAttrs.value = obj.landUrl.split(',').map((v, i) => {
      return {
        name: `位置附件_${i}`,
        url: v,
        uid: 'id_' + Date.now(),
      };
    });
  }
}
// 导入
const onUpload = () => {
  importExcelRef?.value && importExcelRef.value.show();
};
const onDownloadExcel = (url) => {
  downloadFile(url, `土地模版表.xlsx`);
};
const onUploadExcel = (formData) => {
  formData.append('landType', searchCondition.value.landType[searchCondition.value.landType.length - 1]);
  importLands(formData)
    .then((res) => {
      if (res.status === 200) {
        app.$message.success('导入成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导入失败！');
      importExcelRef.value.clear();
    })
    .finally(() => {
      importExcelRef.value.hide();
    });
};

// #endregion
</script>

<style lang="scss" scoped>
.area_form_ {
  display: grid;
  grid-template-columns: 75% 25%;
  ::v-deep() {
    .el-input-number {
      width: 100%;
      .el-input__wrapper {
        border-radius: 4px 0 0 4px;
      }
    }
    .el-select__wrapper {
      border-radius: 0 4px 4px 0 !important;
      border-left: none;
    }
  }
}
</style>
