<template>
  <CustomCard>
    <el-radio-group v-model="landType" class="lands_types" style="margin-bottom: 30px" @change="getList()">
      <el-radio-button v-for="item in landsType" :key="'landsType_' + item.value" :value="item.value">
        {{ item.label }}
      </el-radio-button>
    </el-radio-group>
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      v-model:search="searchData"
      class="custon_create_land_"
      :data="data"
      :option="option"
      :before-close="handleCloseFrom"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      @search-reset="handleResetSearch"
      @search-change="handleSearch"
      @row-save="handleRowSave"
    >
      <template #landTransfer="{ row }">
        {{ row.landTransfer == '1' ? '是' : '否' }}
      </template>
      <template #isUpload="{ row }">
        {{ row.isUpload != '1' ? '是' : '否' }}
      </template>
      <template #menu-left>
        <el-button type="success" icon="upload" @click="handleImport">导入</el-button>
        <el-button type="success" icon="download" @click="handleExport">导出</el-button>
      </template>
      <template #menu="{ row }">
        <el-button type="info" link @click="handleView(row)">查看</el-button>
        <el-popconfirm title="确定删除该土地?" @confirm="() => handleDelete(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
      <template #propertyCertificateUrl-form="{ type }">
        <Attrs v-model:attrs="attrs" :view="type" />
      </template>
      <template #landCertificateUrl-form="{ type }">
        <Attrs v-model:attrs="landOwnerAttrs" :view="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" :view="type" />
      </template>
    </avue-crud>
  </CustomCard>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import CustomCard from '@/components/CustomCard';
import { CRUD_OPTIONS } from '@/config';
import { useUserStore } from '@/store/modules/user';
import { getLandsList, exportLands, delLand, saveLand, importLands } from '@/apis/land.js';
import { ElMessage } from 'element-plus';
import useLandHook from './useLandHook';
import { CommonUpload } from '@/apis';
import Attrs from './common/Attrs.vue';
import { add } from 'lodash';

const { landType, landsType, landClassificationType, handleIficationType } = useLandHook();
const { VITE_APP_BASE_API } = import.meta.env;
const UserStore = useUserStore();

onMounted(() => {
  getList();
});
const params = ref({
  zoom: 10,
});
const local_ = ref([102.833669, 24.88149, '昆明市']);
const local = ref(JSON.parse(JSON.stringify(local_.value)));
/* --------------- data --------------- */
// #region
const crudRef = ref();
const pageData = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const data = ref([]);
const option = reactive({
  ...CRUD_OPTIONS,
  selection: false,
  menuWidth: 120,
  column: [
    {
      label: '地块名',
      prop: 'landName',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '地址',
      prop: 'address',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '产权人',
      prop: 'owner',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '所属网格',
      prop: 'gridName',
      // type: 'select',
      search: true,
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '农用地分类',
      prop: 'landClassificationType',
      select: 'select',
      dicData: landClassificationType,
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '面积',
      prop: 'area',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '坐标',
      prop: 'coordinate',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '是否流转土地',
      prop: 'landTransfer',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '产权编号',
      prop: 'landCode',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '土壤类型',
      prop: 'soilType',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
    {
      label: '是否上传附件',
      prop: 'isUpload',
      addDisplay: false,
      display: false,
      editDisplay: false,
    },
  ],
  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',
          },
          dicMethod: 'get',
          dicHeaders: {
            authorization: UserStore.token,
          },
          dicFormatter: (res) => res?.data?.records ?? [],
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '用地分类',
          prop: 'landClassificationType',
          type: 'select',
          dicData: landClassificationType,
          viewDisplay: false,
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '用地分类',
          prop: 'landClassificationTypeView',
          addDisplay: false,
        },
        {
          label: '位置',
          prop: 'villageCode',
          type: 'cascader',
          props: {
            label: 'areaName',
            value: 'areaCode',
            children: 'areaChildVOS',
          },
          dicUrl: `${VITE_APP_BASE_API}/system/area/region?areaCode=530000`,
          dicHeaders: {
            authorization: UserStore.token,
          },
          dicFormatter: (res) => res.data ?? [],
          // change: (o) => setCityChange(o),
          rules: [
            {
              required: true,
              message: '请选择',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '是否土地流转',
          prop: 'isTransfer',
          type: 'select',
          viewDisplay: false,
          dicData: [
            {
              label: '是',
              value: '0',
            },
            {
              label: '否',
              value: '1',
            },
          ],
        },
        {
          label: '是否土地流转1',
          prop: 'isTransferView',
          addDisplay: false,
        },
        {
          label: '面积',
          prop: 'area',
        },
        {
          label: '产权人',
          prop: 'owner',
        },
        {
          label: '土壤类型',
          prop: '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',
        },
      ],
    },
  ],
});
const searchData = reactive({
  landName: '',
  gridName: '',
  owner: '',
});
const attrs = ref([]);
const landOwnerAttrs = ref([]);
const landAttrs = ref([]);
const rowData = ref([]);
// #endregion

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

async function getList() {
  const params = {
    current: pageData.currentPage,
    size: pageData.pageSize,
    landType: landType.value,
    ...searchData,
  };
  let res = await getLandsList(params);
  if (res.code == 200) {
    data.value = res.data.records;
    data.value.forEach((v) => {
      v.isTransfer = v.landTransfer || 1;
      v.isTransferView = v.landTransfer == 1 ? '否' : '是';
      v.landClassificationTypeView = handleIficationType(v.handleIficationType);
      // v.coordinateView = v.coordinate;
    });
    pageData.total = res.data.total;
  }
}
function handlePageChange(val) {
  pageData.currentPage = val;
  getList();
}
function handleSizeChange(val) {
  pageData.pageSize = val;
  getList();
}
async function handleSearch(form, done) {
  for (let key in form) {
    searchData[key] = form[key];
  }
  await getList();
  done();
}
async function handleResetSearch() {
  for (let key in searchData) {
    searchData[key] = '';
  }
  pageData.currentPage = 1;
  pageData.pageSize = 10;
  pageData.total = 0;
  await getList();
}
const attrNames = reactive(landsType.map((v) => v.label));
function handleImport() {
  let inp = document.createElement('input');
  inp.type = 'file';
  inp.onchange = fileUp;
  document.body.appendChild(inp);
  inp.click();
  document.body.removeChild(inp);
}
async function fileUp(e) {
  let formData = new FormData();
  formData.append('file', e.target.files[0]);
  formData.append('landType', landType.value);
  const res = await importLands(formData);
  if (res.code == 200) {
    ElMessage.success('导入成功');
    getList();
  }
}
async function handleExport() {
  let res = await exportLands({
    landType: landType.value,
  });
  if (res) {
    let a = document.createElement('a');
    a.download = attrNames.value[Number(landType.value)] + '.xlsx';
    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);
  }
}
async function handleDelete(id) {
  let res = await delLand(id);
  if (res.code == 200) {
    getList();
  }
}
function handleView(obj) {
  rowData.value = obj;
  if (obj.propertyCertificateUrl) {
    attrs.value = obj.propertyCertificateUrl.split(',').map((v, i) => {
      return {
        name: `产权附件_${i}`,
        url: v,
        id: 'id_' + Date.now(),
      };
    });
  }
  if (obj.landCertificateUrl) {
    landOwnerAttrs.value = obj.landCertificateUrl.split(',').map((v, i) => {
      return {
        name: `使用信息附件_${i}`,
        url: v,
        id: 'id_' + Date.now(),
      };
    });
    if (obj.landUrl) {
      landAttrs.value = obj.landUrl.split(',').map((v, i) => {
        return {
          name: `位置附件_${i}`,
          url: v,
          id: 'id_' + Date.now(),
        };
      });
    }
  }
  crudRef.value.rowView(obj);
}
function handleCloseFrom(done) {
  landOwnerAttrs.value = [];
  attrs.value = [];
  landAttrs.value = [];
  local.value = JSON.parse(JSON.stringify(local_.value));
  done();
}

async function handleRowSave(val, done, loading) {
  let data = JSON.parse(JSON.stringify(val));
  data.isDraftsSave = 0;
  data.landType = landType.value;
  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.propertyCertificateUrl = urls.join();
  data.landCertificateUrl = landOwnerUrls.join();
  data.landUrl = landUrls.join();
  data.villageCode = data.villageCode[data.villageCode.length - 1] || '';
  // if (local.value.length != 0) {
  //   data.coordinate = `${local.value[0]}E,${local.value[1]}N`;
  // }
  const res = await saveLand(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getList();
    attrs.value = [];
    landOwnerAttrs.value = [];
    done();
  }
}
// #endregion
</script>

<style lang="scss" scoped>
.lands_types {
  justify-content: center;
  width: 100%;
  > label {
    width: 12%;
    ::v-deep() {
      .el-radio-button__inner {
        width: 100%;
      }
    }
  }
}
.create_land_attrs_content_ {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
  gap: 20px;
  .custom-form__uploader {
    box-sizing: border-box;
    height: auto;
  }
  > div {
    width: calc(50% - 10px);
    aspect-ratio: 1 / 1;
  }
  .attrs_content__item {
    box-sizing: border-box;
    position: relative;
    padding: 6px;
    border: 1px solid #ccc;
    border-radius: 4px;
    img {
      width: 100%;
      height: 100%;
      border-radius: 2px;
    }
    .clear_btn {
      position: absolute;
      right: 0px;
      top: 0px;
      font-size: 18px;
      color: #f15c5c;
      opacity: 0;
      cursor: pointer;
      background-color: #fff;
      border-radius: 50%;
    }
    &:hover {
      .clear_btn {
        opacity: 1;
      }
    }
  }
}
</style>
