<template>
  <section class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model:page="page"
      v-model:search="searchData"
      :option="option"
      :data="data"
      :table-loading="_loading"
      :before-open="handleOpenFrom"
      :before-close="handleCloseFrom"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      @search-change="handleSearch"
      @search-reset="handleResetSearch"
      @row-save="handleRowSave"
      @row-update="handleExamine"
      @cell-click="handleCellClick"
    >
      <template #menu="{ row }">
        <el-button link type="primary" @click="handleInfo(row)">查看</el-button>
        <el-button link type="primary" @click="handleInfo(row)">案件处理</el-button>
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, reactive, h, onMounted, watch } from 'vue';
import { CRUD_OPTIONS } from '@/config';
import { useUserStore } from '@/store/modules/user';
import Register from './common/Register.vue';
import FileUpload from './common/FileUpload.vue';
import { getIllegalList, createLandIllegal, registerLandIllegal, illegalInfo } from '@/apis/land';
import { ElMessage, ElMessageBox } from 'element-plus';
import Attrs from '../../common/Attrs.vue';
import { add } from 'lodash';

const { VITE_APP_BASE_API } = import.meta.env;
const UserStore = useUserStore();

onMounted(getList);

/* --------------- data --------------- */
// #region
const crudRef = ref();
const searchData = ref({
  caseId: '',
  status: '',
});
const page = ref({
  currentPage: 1,
  pageSize: 10,
  total: 3,
});
const _loading = ref(false);
const data = ref([]);
const landsArr = ref([]);
const resultData = ref([
  {
    label: '正常营业，无违规行为',
    value: 1,
  },
  {
    label: '简易程序，当场行政处罚',
    value: 2,
  },
  {
    label: '普通程序，当场处罚立案审批',
    value: 3,
  },
  {
    label: '移送程序，案件移送',
    value: 4,
  },
  {
    label: '特殊程序，案件终止',
    value: 5,
  },
]);
const documentData = ref([
  {
    label: '协助调查函',
    value: 1,
  },
  {
    label: '抽样取样凭证',
    value: 2,
  },
  {
    label: '检测报告',
    value: 3,
  },
  {
    label: '其他文书',
    value: 4,
  },
]);
const option = ref({
  ...CRUD_OPTIONS,
  refreshBtn: false,
  index: false,
  rowKey: 'caseId',
  editTitle: '案件登记处理',
  selection: false,
  addBtn: false,
  column: [
    {
      label: '违法行为',
      prop: 'illegalTypeName',
      search: true,
      editDisplay: false,
      viewDisplay: false,
      type: 'select',
      dicData: [
        { label: '未处理', value: 0 },
        { label: '已处理', value: 1 },
      ],
      // rules: [
      //   {
      //     required: true,
      //     message: '请选择',
      //     trigger: 'blur',
      //   },
      // ],
    },
    {
      label: '违法行为描述',
      prop: 'desc',
      editDisplay: false,
      viewDisplay: false,
      rules: [
        {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      ],
    },
    {
      label: '任务编号',
      prop: 'illegalTypeCode',
      search: true,
      editDisplay: false,
      viewDisplay: false,
      rules: [
        {
          required: true,
          message: '请输入任务编号',
          trigger: 'blur',
        },
      ],
    },
    {
      label: '巡查任务名称',
      prop: 'inspectionTaskName',
      editDisplay: false,
      viewDisplay: false,
    },
    {
      label: '巡查任务对象',
      prop: 'inspectionTaskTarget',
      addDisplay: true,
      editDisplay: false,
      viewDisplay: false,
    },
    {
      label: '状态',
      prop: 'status',
      addDisplay: true,
      editDisplay: false,
      viewDisplay: false,
    },
  ],
  group: [
    {
      label: '案件信息>',
      prop: 'caseInfo',
      addDisplay: false,
      column: [
        {
          label: '案件名称',
          prop: 'caseName',
          render: ({ row }) => {
            return h('span', {}, row.caseName);
          },
        },
        {
          label: '案件编号',
          prop: 'caseId',
          render: ({ row }) => {
            return h('span', {}, row.caseId);
          },
        },
        {
          label: '关联单位',
          prop: 'relatedUnit',
          render: ({ row }) => {
            return h('span', {}, row.relatedUnit);
          },
        },
        {
          label: '关联地块',
          prop: 'relatedLandname',
          render: ({ row }) => {
            return h('span', {}, row.relatedLandname);
          },
        },
        {
          label: '法定代表人',
          prop: 'legalPerson',
          render: ({ row }) => {
            return h('span', {}, row.legalPerson);
          },
        },
        {
          label: '联系电话',
          prop: 'phone',
          render: ({ row }) => {
            return h('span', {}, row.phone);
          },
        },
        {
          label: '统一社会信用代码',
          prop: 'usciCode',
          span: 24,
          render: ({ row }) => {
            return h('span', {}, row.usciCode);
          },
        },
        {
          label: '违法情况',
          prop: 'violationSituation',
          span: 24,
          render: ({ row }) => {
            return h('span', {}, row.violationSituation);
          },
        },
      ],
    },
    {
      label: '案件处理>',
      prop: 'caseHandle',
      addDisplay: false,
      column: [
        {
          label: '案情记录',
          prop: 'caseRecord',
          type: 'textarea',
          span: 24,
          display: true,
          editDisplay: true,
          rules: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '现场取证',
          prop: 'sceneProof',
          span: 24,
          display: true,
          editDisplay: true,
        },
        {
          label: '执法文书',
          prop: 'lawDocument',
          span: 24,
          type: 'radio',
          viewDisplay: false,
          addDisplay: false,
          dicData: documentData.value,
          rules: [
            {
              required: true,
              message: '请选择',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '执法文书',
          prop: 'lawDocument',
          span: 24,
          addDisplay: false,
          editDisplay: false,
          viewDisplay: true,
          render: ({ row }) => {
            return h('span', {}, documentData.value.find((item) => item.value == row.lawDocument)?.label);
          },
        },
        {
          label: '',
          prop: 'attrs_',
          span: 24,
        },
      ],
    },
    {
      label: '处理结果>',
      prop: 'caseResult_',
      addDisplay: false,
      column: [
        {
          label: '案件处理结果',
          prop: 'caseResult',
          type: 'radio',
          dicData: resultData.value,
          span: 24,
          addDisplay: false,
          viewDisplay: false,
          rules: [
            {
              required: true,
              message: '请选择',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '案件处理结果',
          prop: 'caseResult',
          span: 24,
          addDisplay: false,
          editDisplay: false,
          render: ({ row }) => {
            return h('span', {}, resultData.value.find((item) => item.value == row.caseResult)?.label);
          },
        },
      ],
    },
  ],
});
const caseInfo = ref({
  visible: false,
});
const examineForm = reactive({
  caseId: '',
  proof: [],
  attrs: [],
});
watch(
  () => examineForm,
  () => {
    console.log('examineForm', examineForm.attrs);
  },
  {
    deep: true,
    immediate: true,
  }
);
// #endregion

/* --------------- methods --------------- */

// #region

async function getList() {
  // _loading.value = true;
  let params = {
    illegalFlag: 1,
    current: page.value.currentPage,
    size: page.value.pageSize,
    // ...searchData.value,
  };
  let res = await getIllegalList(params);
  console.log('res -- ', res);
  _loading.value = false;
  if (res.code == 200) {
    data.value = res.data.records;
    page.value.total = res.data.total;
  }
}
function handlePageChange(val) {
  page.value.currentPage = val;
  getList();
}
function handleSizeChange(val) {
  page.value.currentPage = 1;
  page.value.pageSize = val;
  getList();
}
function handleInfo(row) {
  console.log('row', row);
  // examineForm.caseId = row.caseId;
  // // caseInfo.value.visible = true;
  // crudRef.value.rowEdit(row);
  // // crudRef.value.rowView(row);
}
async function handleSearch(form, done) {
  page.value.currentPage = 1;
  await getList();
  done();
}
async function handleResetSearch() {
  page.value.currentPage = 1;
  await getList();
}

async function handleRowSave(val, done, loading) {
  let data = {
    caseId: val.caseId,
    caseName: val.caseName,
    relatedUnit: val.relatedUnit,
    relatedLand: val.landId,
    phone: val.phone,
    legalPerson: val.legalPerson,
    usciCode: val.usciCode,
    violationSituation: val.violationSituation,
  };
  if (val.landId) {
    data.relatedLandname = landsArr.value.find((item) => item.id == val.landId).landName;
  }
  console.log('val', data);
  let res = await createLandIllegal(data);
  if (res.code == 200) {
    ElMessage.success('创建成功');
    getList();
    done();
    ElMessageBox.confirm('土地违法案件信息已添加，是否现在添加案件处理信息与结果。后续也可以单独添加。', '案件信息已添加', {
      confirmButtonText: '是，现在添加',
      cancelButtonText: '否，后续添加',
      type: 'success',
    }).then(() => {
      getDetails(val.caseId);
    });
  }
  loading();
}

async function handleExamine(val, done, loading) {
  let data = {
    caseId: examineForm.caseId,
    caseRecord: val.caseRecord,
    caseResult: val.caseResult,
    lawDocument: val.lawDocument,
  };
  if (examineForm.proof.length > 0) {
    data.evidenceFile = examineForm.proof.map((v) => v.url).join();
  }
  if (examineForm.attrs.length > 0) {
    data.lawFile = examineForm.attrs.map((v) => `${v.name}&${v.url}`).join();
  }
  let res = await registerLandIllegal(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('提交成功');
    getList();
  }
}
async function getDetails(id, type = 'add') {
  examineForm.caseId = id;
  let res = await illegalInfo(id);
  if (res.code == 200) {
    console.log('detaile', res);
    if (res.data.evidenceFile) {
      examineForm.proof = res.data.evidenceFile.split(',').map((v, i) => {
        return {
          url: v,
          uid: `id_${i}_${Date.now()}`,
        };
      });
    }
    if (res.data.lawFile) {
      examineForm.attrs = res.data.lawFile.split(',').map((v, i) => {
        let [name, url] = v.split('&');
        return {
          name,
          url,
          uid: `id_${i}_${Date.now()}`,
          status: 'success',
        };
      });
    }
    type == 'add' ? crudRef.value.rowEdit(res.data) : crudRef.value.rowView(res.data);
  }
}
const cellClick = ref(['caseId', 'caseName']);
function handleCellClick(row, column) {
  if (cellClick.value.includes(column.columnKey)) {
    getDetails(row.caseId, 'view');
  }
}
function handleOpenFrom(done, type) {
  console.log('form open', type);
  let lab = type == 'view' ? '执法文书附件' : '';
  if (type == 'view') {
    option.value.group.find((v) => v.prop == 'caseHandle').column.find((v) => v.prop == 'attrs_').label = lab;
  }
  // done();
}
function handleCloseFrom(done) {
  console.log('form close');
  examineForm.caseId = '';
  examineForm.proof = [];
  examineForm.attrs = [];
  done();
}
// #endregion
</script>

<style lang="scss" scoped>
.proof_content_ {
  display: flex;
  > section {
    flex: 1;
  }
}
::v-deep() {
  .attrs_ {
    .el-form-item__label {
      opacity: 0;
    }
  }
}
</style>
