<template>
  <div class="custom-page">
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <pane size="16">
          <el-col>
            <custom-table-tree title="疫病分类" :data="treeData" @node-click="onNodeClick" />
          </el-col>
        </pane>
        <pane size="84">
          <el-col>
            <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="primary" icon="plus" @click="rowAdd">添加</el-button>
                <el-button type="danger" icon="delete" @click="onDel(state.selection)">批量删除</el-button>
              </template>

              <template #reportUrl-form="{ column, value }">
                <el-upload
                  v-model:file-list="state.fileList"
                  action="#"
                  :show-file-list="true"
                  list-type="picture-card"
                  accept="image/*"
                  :http-request="rowUploadPicture"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </template>

              <template #reportLink-form="{ column, value }">
                <el-button type="primary" text @click="downloadFile(value, `${state.currentRow?.name}-检测报告.png`, 'image')"> 下载 </el-button>
              </template>

              <template #result-form="{ column, value }">
                <el-button type="primary" style="margin-bottom: 16px" @click="addInfo(value)">新增</el-button>
                <el-table :data="value" style="width: 100%" border>
                  <el-table-column prop="c1" label="检测项目" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.c1" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="c2" label="检测方法" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.c2" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="c3" label="主要试剂" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.c3" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="c4" label="检测结果" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.c4" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="c5" label="备注" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.c5" type="textarea" rows="2" :disabled="scope.row.disabled" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="130" align="center">
                    <template #default="scope">
                      <el-button type="primary" icon="edit" text @click="editInfo(scope.row)"></el-button>
                      <el-button type="danger" icon="delete" text @click="delInfo(value, scope.row, scope.$index)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>

              <template #customInfo-form="{ column }">
                <custom-info :row="state.currentRow" />
              </template>

              <template #menu="scope">
                <custom-table-operate :actions="state.options.actions" :data="scope" />
              </template>
            </avue-crud>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useApp } from '@/hooks';
import { useUserStore } from '@/store/modules/user';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, mockData, sleep, downloadFile } from '@/utils';
import CustomInfo from './info.vue';

const { VITE_APP_BASE_API, VITE_APP_NAME } = 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,
    addBtn: false,
    selection: true,
    column: [
      {
        label: '疫病名称',
        prop: 'p1',
        search: true,
        width: 200,
        hide: true,
        display: false,
      },
      {
        label: '数据来源',
        prop: 'p2',
        width: 200,
        overHidden: true,
        type: 'select',
        dicData: [
          {
            label: '动物疾病预防中心',
            value: '1',
          },
          {
            label: '动物疾病监测站',
            value: '2',
          },
          {
            label: '动植物检测检疫公司',
            value: '3',
          },
        ],
        // hide: true,
        // addDisplay: true,
        // editDisplay: true,
        // viewDisplay: false,
        // 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 ?? [],
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '报告编号',
        prop: 'p3',
        width: 150,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
      },
      {
        label: '送检单位',
        prop: 'p4',
        width: 200,
        overHidden: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '送检人',
        prop: 'p5',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '联系电话',
        prop: 'p51',
        width: 150,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '送检日期',
        prop: 'p6',
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '样品名称',
        prop: 'p7',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '样品数量',
        prop: 'p71',
        width: 150,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '样品状态',
        prop: 'p72',
        type: 'select',
        dicData: [
          {
            label: '良好',
            value: '1',
          },
          {
            label: '一般',
            value: '2',
          },
          {
            label: '异常',
            value: '3',
          },
        ],
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '检测报告',
        prop: 'reportUrl',
        hide: true,
        formslot: true,
        span: 24,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
      },
      {
        label: '检测报告',
        prop: 'reportLink',
        hide: false,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
      },
      {
        label: '检测项目',
        prop: 'p8',
        width: 200,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: false,
      },
      {
        label: '检测结果',
        prop: 'p9',
        span: 24,
        rows: 4,
        width: 200,
        overHidden: true,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: false,
      },
      {
        label: '创建时间',
        prop: 'createTime',
        width: 200,
        search: true,
        display: false,
      },
      {
        label: '更新时间',
        prop: 'updateTime',
        width: 200,
        display: false,
      },
      {
        label: '检测信息',
        prop: 'result',
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
        span: 24,
      },
      {
        label: '',
        labelWidth: 0,
        prop: 'customInfo',
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
        span: 24,
      },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => rowView(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  fileList: [],
  currentRow: {},
});

// tree
const treeData = ref([
  // {
  // label: '疫病分类',
  // id: '0',
  // children: [
  { label: '家禽类', id: '01', children: [], pId: '0' },
  { label: '家畜类', id: '02', children: [], pId: '0' },
  { label: '水产类', id: '03', children: [], pId: '0' },
  { label: '特种养殖类', id: '04', children: [], pId: '0' },
  //   ],
  // },
]);

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;
  //   });

  state.loading = true;
  await sleep(500);
  state.data = mockData(
    {
      p2: '动物疾病监测中心',
      p3: 'h1234567',
      p4: '畜牧养殖基地',
      p5: '张三',
      p51: '13837498523',
      p6: '2025-01-20',
      p7: '全血',
      p71: '3份',
      p72: '良好',
      p8: '猪瘟',
      p9: '检测样品4分，阴性4份，阳性0份',
      createTime: '2025-01-20',
      updateTime: '2025-01-25',
    },
    10
  );
  state.loading = false;
};

loadData();

const onNodeClick = (data) => {
  console.log('onNodeClick', data);
};

// 页数
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) => {
  state.currentRow = { ...row, reportViewUrl: row.reportUrl };
  crudRef.value.rowView(state.currentRow);
};

// 新增
const rowAdd = () => {
  state.form = {
    result: [],
  };
  crudRef.value.rowAdd(state.form);
};
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) => {
  if (!isEmpty(row.result)) {
    row.result.forEach((item) => {
      item.disabled = true;
    });
  }
  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 addInfo = (list = []) => {
  list.push({
    c1: '',
    c2: '',
    c3: '',
    c4: '',
    c5: '',
    disabled: false,
  });
};

const editInfo = (row) => {
  row.disabled = false;
};

const delInfo = (list, row, index) => {
  list.splice(index, 1);
};
</script>
