<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model="state.form"
      v-model:search="state.query"
      v-model:page="state.pageData"
      :table-loading="state.loading"
      :data="state.data"
      :option="state.options"
      @refresh-change="refreshChange"
      @search-reset="searchChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @row-del="rowDel"
      @row-save="rowSave"
      @row-update="rowUpdate"
    >
      <template #menu-left>
        <el-button type="danger" icon="delete" @click="onDel(state.selection)">批量删除</el-button>
      </template>

      <template #status="{ row }">
        <el-tag v-if="row.status == 1" type="success">启用</el-tag>
        <el-tag v-if="row.status == 0" type="danger">禁用</el-tag>
      </template>

      <template #menu="scope">
        <custom-table-operate :actions="state.options.actions" :data="scope" />
      </template>
    </avue-crud>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useApp } from '@/hooks';
import { useUserStore } from '@/store/modules/user';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, setDicData, debounce } from '@/utils';
import { CommonDicData } from '@/apis';
import { getLandsList } from '@/apis/land';
import { GetEntityList, AddEntity, UpdateEntity, DeleteEntity, UpdateStatus } from '@/apis/plantingAndBreeding/base';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const router = useRouter();
const crudRef = ref(null);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    selection: true,
    column: [
      {
        label: '基地名称',
        prop: 'baseName',
        search: true,
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
        overHidden: true,
      },
      {
        label: '基地类型',
        prop: 'baseType',
        type: 'select',
        search: true,
        props: {
          label: 'dictLabel',
          value: 'dictValue',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/dict/data/type/sys_base_type`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data ?? [],
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '地块名',
        prop: 'landName',
        width: 200,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
        overHidden: true,
      },
      {
        label: '地块名',
        prop: 'landId',
        width: 200,
        type: 'select',
        hide: true,
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
        props: {
          label: 'landName',
          value: 'id',
        },
        dicUrl: `${VITE_APP_BASE_API}/land-resource/landManage/page?current=1&size=20`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data?.records ?? [],
        filterable: true,
        remote: true,
        clearable: true,
        remoteMethod: (val) => debounce(remoteLandList(val), 200),
        change: (val) => selectedChange(val),
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '区域位置',
        prop: 'address',
        width: 200,
        overHidden: true,
        disabled: true,
        labelTip: '请先选择地块！',
      },
      {
        label: '区域面积',
        prop: 'area',
        width: 150,
        overHidden: true,
        disabled: true,
        labelTip: '请先选择地块！',
        formatter: (row) => {
          const item = state.unitList.find((v) => v.dictValue == row.unit);
          return row.area + (!isEmpty(item) ? item.dictLabel : '平方米');
        },
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        dicData: [
          {
            label: '启用',
            value: 1,
          },
          {
            label: '禁用',
            value: 0,
          },
        ],
        value: 1,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '负责人',
        prop: 'contactPerson',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '联系电话',
        prop: 'contactPhone',
        width: 150,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '创建时间',
        prop: 'createdAt',
        width: 200,
        display: false,
      },
      {
        label: '更新时间',
        prop: 'updatedAt',
        width: 200,
        display: false,
      },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => rowView(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'primary',
        name: ({ row }) => {
          return row.status === 1 ? '禁用' : '启用';
        },
        icon: ({ row }) => {
          return row.status === 1 ? 'turnOff' : 'open';
        },
        event: ({ row }) => rowStatus(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  unitList: [],
});

// 加载
const getUnit = async () => {
  CommonDicData('sys_unit_type')
    .then((res) => {
      console.log(250, res);
      if (res.code === 200) {
        state.unitList = res.data;
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    });
};

const loadData = async () => {
  state.loading = true;
  GetEntityList(state.query)
    .then((res) => {
      if (res.code === 200) {
        const { current, size, total, records } = res.data;
        state.data = records;
        state.pageData = {
          currentPage: current || 1,
          pageSize: size || 10,
          total: total,
        };
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

loadData();

onMounted(() => {
  getUnit();
});

// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = (params, done) => {
  if (done) done();
  state.query = params;
  state.query.current = 1;
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

// 查看
const rowView = (row) => {
  crudRef.value.rowView(row);
};

// 启用、禁用
const rowStatus = (row) => {
  let status = row.status === 1 ? 0 : 1;
  UpdateStatus({ id: row.id, status })
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('状态更改成功！');
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    });
};

// 新增
const rowSave = (row, done, loading) => {
  AddEntity(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('添加成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 编辑
const rowEdit = (row) => {
  crudRef.value && crudRef.value.rowEdit(row);
};

const rowUpdate = (row, index, done, loading) => {
  UpdateEntity(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('更新成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 删除
const onDel = (rows = []) => {
  if (isEmpty(rows)) return;
  const ids = rows.map((item) => item.id);
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      DeleteEntity({ ids: ids.join(',') })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

const rowDel = (row, index, done) => {
  onDel([row]);
};

// 远程搜搜
const remoteLandList = async (val) => {
  const query = { landName: val, current: 1, size: 20 };
  const res = await getLandsList(query);
  if (res.code === 200) {
    setDicData(state.options.column, 'landId', res.data.records);
  }
};

// 选择赋值
const selectedChange = ({ item, value, dic }) => {
  // console.log(390, value, item);
  crudRef.value.tableForm.landId = value;
  crudRef.value.tableForm.landName = item?.landName;
  crudRef.value.tableForm.address = item?.address;
  crudRef.value.tableForm.area = item?.area;
  crudRef.value.tableForm.unit = item?.landUnit;
  crudRef.value.tableForm.provinceCode = item?.provinceCode;
  crudRef.value.tableForm.cityCode = item?.cityCode;
  crudRef.value.tableForm.districtCode = item?.county;
  crudRef.value.tableForm.townCode = item?.townCode;
  crudRef.value.tableForm.villageCode = item?.villageCode;
};
</script>
