<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div :class="`${prefixCls}`">
      <div :class="`${prefixCls}-header`">
        <div>
          <a-button type="primary" :icon="h(StarOutlined)" @click="openCollenction">
            收藏夹（ {{ favoriteNum }} ）
          </a-button>
        </div>
        <div class="flex">
          <a-tree-select
            v-if="selectOptions1.length > 0"
            v-model:value="selectValues1"
            show-search
            style="width: 230px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="查询地区"
            allow-clear
            :tree-data="selectOptions1"
            :field-names="{
              children: 'children',
              value: 'id',
              label: 'name',
            }"
            tree-node-filter-prop="name"
            @change="areaChange"
          />
          <a-select
            ref="select"
            v-model:value="is_illegal"
            style="width: 150px"
            class="ml-3"
            allowClear
            :options="selectOptions2"
            placeholder="现场状况"
            @change="reload1"
          />
          <a-select
            ref="select"
            v-model:value="is_drawback"
            :options="selectOptions3"
            style="width: 150px"
            class="ml-3"
            allowClear
            placeholder="新增退回"
            @change="reload1"
          />
          <a-input
            style="width: 150px"
            class="ml-3"
            v-model:value="searchKey"
            placeholder="请输入"
          />
          <a-button class="ml-3" :icon="h(SearchOutlined)" @click="reload1">搜索</a-button>
          <a-button type="success" class="ml-3" :icon="h(DownloadOutlined)">导出</a-button>
        </div>
      </div>
      <div :class="`${prefixCls}-content`">
        <div :class="`${prefixCls}-content-tabbox`">
          <div :class="`${prefixCls}-content-tabbox-left`">
            <BasicTable @register="registerTable" v-if="!collenctionVisible">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <TableAction
                    :actions="[
                      {
                        label: '收藏',
                        color: 'warning',
                        onClick: () => {
                          handleCollention(record);
                        },
                      },
                      {
                        label: '审核',
                        onClick: () => {
                          handleAuditing(record);
                        },
                      },
                    ]"
                  />
                </template>
              </template>
            </BasicTable>
            <div :class="`${prefixCls}-content-tabbox-left-collenction`" v-if="collenctionVisible">
              <div :class="`${prefixCls}-content-tabbox-left-collenction-header`">
                <div> <StarOutlined /> 收藏案件 </div>
                <div
                  :class="`${prefixCls}-content-tabbox-left-collenction-header-close`"
                  @click="closeCollenction"
                  ><CloseOutlined
                /></div>
              </div>
              <div>
                <BasicTable @register="registerCollenctionTable">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'action'">
                      <TableAction
                        :actions="[
                          {
                            label: '移除',
                            type: 'link',
                            color: 'warning',
                            onClick: () => {
                              handleRemoveCollention(record);
                            },
                          },
                          {
                            label: '审核',
                            onClick: () => {
                              handleAuditing(record);
                            },
                          },
                        ]"
                      />
                    </template>
                  </template>
                </BasicTable>
              </div>
            </div>
          </div>
          <div :class="`${prefixCls}-content-tabbox-right`" v-if="auditingVisible">
            <div :class="`${prefixCls}-content-tabbox-right-header`">
              <div
                :class="`${prefixCls}-content-tabbox-right-header-tabs`"
                v-for="(item, index) in tabsArr"
                :key="index"
              >
                <div
                  :class="tabsActiveIndex == index ? 'active' : 'tabsnormal'"
                  @click="tabsClick(index)"
                  >{{ item }}</div
                >
              </div>
              <div :class="`${prefixCls}-content-tabbox-right-header-close`" @click="auditingClose"
                ><CloseOutlined
              /></div>
            </div>
            <div :class="`${prefixCls}-content-tabbox-right-content`">
              <BasicForm ref="formRef" @register="registerForm" v-show="tabsActiveIndex == 0">
                <template #imgSlot>
                  <div
                    v-for="(item, num) in fileList"
                    :key="num"
                    style="
                      position: relative;
                      width: 125px;
                      height: 90px;
                      overflow: hidden;
                      float: left;
                      background: #f9f9f9;
                      margin-left: 6px;
                      margin-bottom: 6px;
                    "
                  >
                    <a-image :width="125" :src="item.url" />
                  </div>
                  <a-empty v-show="fileList.length <= 0">
                    <template #description>
                      <span>暂无图片</span>
                    </template>
                  </a-empty>
                </template>
                <template #videoSlot>
                  <video
                    width="240"
                    height="150"
                    controls
                    v-for="(item, index) in videoList"
                    :key="index"
                  >
                    <source :src="item" type="video/mp4" />
                    您的浏览器不支持Video标签。
                  </video>
                  <a-empty v-show="videoList.length <= 0">
                    <template #description>
                      <span>暂无视频</span>
                    </template>
                  </a-empty>
                </template>
              </BasicForm>
              <HandleCase :id="selectRowDetail.id" v-show="tabsActiveIndex == 1" />
            </div>
            <div :class="`${prefixCls}-content-tabbox-right-footer`">
              <a-input class="ml-3" v-model:value="caseBackReason" placeholder="案件退回原因" />
              <a-button type="error" class="ml-3" @click="handleCaseBack"> 退回 </a-button>
              <a-button type="primary" class="ml-3" @click="handlePassForm"> 通过 </a-button>
            </div>
          </div>
        </div>
        <div :class="`${prefixCls}-content-mapbox`">
          <MapDetail :ruleForm="selectRowDetail"></MapDetail>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, ref, h } from 'vue';
  import {
    SearchOutlined,
    StarOutlined,
    DownloadOutlined,
    CloseOutlined,
  } from '@ant-design/icons-vue';
  import HandleCase from './HandleCase.vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form';
  import { PageWrapper } from '@/components/Page';
  import {
    getTableDataList,
    addCaseCollection,
    delCaseCollection,
    getCollectionCaseList,
    getUserInfoData,
    getCaseDataDetail,
    getCaseList,
    caseAudiSteps,
    caseBackSteps,
  } from '@/api/caseauditing/index';
  import { getDeptList } from '@/api/demo/system';
  import { columns, formSchema } from './index.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { MapDetail } from '@/views/demo/summaryverification/index';

  const { createMessage } = useMessage();
  const favoriteNum: any = ref();
  const tabsActiveIndex: any = ref('0');
  const tabsArr: any = ref(['案件信息', '核查办理']);
  const auditingVisible: any = ref(false);
  const collenctionVisible: any = ref(false);
  const collenctionList: any = ref([]);
  const selectRowDetail: any = ref({});
  const caseBackReason: any = ref();
  const selectValues1: any = ref();
  const selectOptions1: any = ref([]);
  const videoList: any = ref([]);
  const searchKey: any = ref();
  const countyid: any = ref();
  const streetid: any = ref();
  const communityid: any = ref();
  const is_illegal: any = ref();
  const selectOptions2: any = ref([
    { label: '合法', value: 0 },
    { label: '违法', value: 1 },
    { label: '伪变化', value: 2 },
  ]);
  const is_drawback: any = ref();
  const selectOptions3: any = ref([
    { label: '新增', value: 0 },
    { label: '退回', value: 1 },
  ]);

  const fileList: any = ref([]);

  const [registerTable, { reload: reload1 }] = useTable({
    title: '',
    api: getTableDataList,
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
    },
    isTreeTable: true,
    striped: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: (data) => {
      let temp = {
        page: data.page,
        limit: data.limit,
        is_illegal: is_illegal.value,
        is_drawback: is_drawback.value,
        countyid: countyid.value,
        streetid: streetid.value,
        communityid: communityid.value,
        key: searchKey.value,
      };
      return temp;
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });
  const [registerCollenctionTable, { reload: reload2 }] = useTable({
    title: '',
    api: getCollectionCaseList,
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
    },
    isTreeTable: true,
    striped: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });
  const [registerForm, { setFieldsValue }] = useForm({
    labelWidth: 120,
    labelAlign: 'right',
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });
  function areaChange(items) {
    countyid.value = null;
    streetid.value = null;
    communityid.value = null;
    if (items && JSON.stringify(items).length == 6) {
      countyid.value = items;
    }
    if (items && JSON.stringify(items).length == 9) {
      streetid.value = items;
    }
    if (items && JSON.stringify(items).length == 12) {
      communityid.value = items;
    }
    reload1();
  }

  function handlePassForm() {
    const param = {
      id: selectRowDetail.value.id,
    };
    caseAudiSteps(param).then((res) => {
      if (res) {
        createMessage.success('审核成功');
        setTimeout(() => {
          reload1();
          reload2();
        }, 500);
      }
    });
  }
  function handleCaseBack() {
    if (!caseBackReason.value) {
      createMessage.error('退回原因不能为空');
      return;
    }
    const param = {
      id: selectRowDetail.value.id,
      drawbackReason: caseBackReason.value,
    };
    caseBackSteps(param).then((res) => {
      if (res) {
        createMessage.success('操作成功');
      } else {
        createMessage.error('此案件未办理，无需退回。');
      }
    });
  }
  function handleAuditing(record) {
    const formData = record;
    caseBackReason.value = null;
    formData.homeAddress =
      record.countyname + record.streetname + record.communityname + record.address;
    formData.lngLat = record.lng + ' , ' + record.lat;
    selectRowDetail.value = formData;
    auditingVisible.value = true;
    setTimeout(() => {
      setFieldsValue(formData);
    }, 100);
    const param = {
      id: record.id,
    };
    getCaseDataDetail(param).then((res) => {
      fileList.value = [];
      videoList.value = [];
      if (res.pics) {
        res.pics.forEach((item) => {
          fileList.value.push({
            url: 'http://60.213.14.14:6070/' + item.path,
            id: item.id,
          });
        });
      }
      if (res.video_list) {
        res.video_list.forEach((item) => {
          videoList.value.push('http://60.213.14.14:6070/' + item);
        });
      }
    });
  }
  function handleCollention(row) {
    getUserInfoData().then((res) => {
      let param = {
        caseNo: row.case_no,
        favoriteUserId: res.user.Id,
      };
      addCaseCollection(param).then((rel) => {
        if (rel) {
          createMessage.success('收藏成功');
          getCollentionLength();
          reload2();
          getCaseCollList();
        }
      });
    });
  }
  function handleRemoveCollention(row) {
    const arr = collenctionList.value.filter((item) => {
      return item.caseNo == row.case_no;
    });
    let param = [arr[0].id];
    delCaseCollection(param).then((res) => {
      if (res) {
        createMessage.success('已从收藏夹中移除');
        getCollentionLength();
        reload2();
      }
    });
  }
  function openCollenction() {
    collenctionVisible.value = true;
  }
  function closeCollenction() {
    collenctionVisible.value = false;
    reload1();
  }
  function tabsClick(index: any) {
    tabsActiveIndex.value = index;
  }
  function auditingClose() {
    auditingVisible.value = false;
  }
  function getCollentionLength() {
    getCollectionCaseList().then((res) => {
      favoriteNum.value = res.total;
    });
  }
  function getOrgList() {
    getDeptList().then((res) => {
      res.forEach((item) => {
        if (item.id == '371300') {
          selectOptions1.value = item.children;
        }
      });
    });
  }
  function getCaseCollList() {
    getUserInfoData().then((res) => {
      getCaseList({ uid: res.user.Id }).then((rel) => {
        collenctionList.value = rel;
      });
    });
  }
  onMounted(() => {
    getCollentionLength();
    getCaseCollList();
    getOrgList();
  });
  const prefixCls = 'form-box';
</script>
<style lang="less" scoped>
  .form-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    &-header {
      width: 100%;
      padding: 0 10px;
      height: 60px;
      background: #f8f8f8;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    &-content {
      width: 100%;
      height: calc(100% - 60px);
      display: flex;

      &-tabbox {
        width: 70%;
        display: flex;
        justify-content: space-between;

        &-left {
          flex: 1;
          border: 1px solid #eee;

          &-collenction {
            display: flex;
            flex-direction: column;
            height: 100%;

            &-header {
              padding: 0 10px;
              height: 50px;
              overflow: auto;
              border-bottom: 1px solid #eee;
              display: flex;
              background: #fff;
              align-items: center;
              justify-content: space-between;

              &-close {
                cursor: pointer;
              }
            }
          }
        }

        &-right {
          flex: 1;
          margin-left: 15px;
          margin-bottom: 15px;
          border: 1px solid #eee;
          background: #fff;

          &-header {
            position: relative;
            padding: 0 10px;
            height: 50px;
            overflow: auto;
            border-bottom: 1px solid #eee;
            display: flex;

            &-tabs {
              cursor: pointer;
              margin: 0 10px;

              .active {
                color: #409eff;
                height: 100%;
                display: flex;
                align-items: center;
              }

              .tabsnormal {
                height: 100%;
                display: flex;
                align-items: center;
                &:hover {
                  color: #409eff;
                  border-bottom: 1px solid #409eff;
                }
              }
            }

            &-close {
              position: absolute;
              right: 20px;
              top: 50%;
              transform: translate(0, -50%);
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }

          &-content {
            height: calc(100% - 140px);
            overflow: auto;
            padding: 15px 20px 15px 10px;
            margin: 10px 0;
          }

          &-footer {
            height: 60px;
            border-top: 1px solid #eee;
            display: flex;
            align-items: center;
            padding-right: 15px;
          }
        }
      }

      &-mapbox {
        width: calc(30% - 20px);
        margin: 0 15px 15px 15px;
        border: 1px solid #eee;
      }
    }
  }
</style>
