<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="securityRecordId"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        :expand-icon-column-index="1"
        :scroll="{ x: 1200 }"
        cache-key="towerModel"
      >
        <template #toolbar>
          <a-space>
            <ProjectSelectModel
              :placeholder="`请选择项目`"
              v-model:value="projectName"
              @done="chooseProject"
            />
            <a-radio-group v-model:value="searchStatus" @change="onStatus">
              <a-radio-button value="0">正常</a-radio-button>
              <a-radio-button value="1">待修</a-radio-button>
              <a-radio-button value="2">异常已修</a-radio-button>
              <a-radio-button value="3">异常未修</a-radio-button>
            </a-radio-group>
            <a-range-picker
              v-model:value="dateRange"
              @change="onRange"
              value-format="YYYY-MM-DD"
              class="ele-fluid"
            />
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userId'">
            {{ `${record.nickname}` }}
          </template>
          <template v-if="column.key === 'images'">
            <a-image :src="record.images" :width="120" />
          </template>
          <template v-if="column.key === 'longitude'">
            {{ `${record.longitude}, ${record.latitude}` }}
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status == 0">正常</a-tag>
            <a-tag v-if="record.status == 1" color="red">待修</a-tag>
            <a-tag v-if="record.status == 2" color="green">异常已修</a-tag>
            <a-tag v-if="record.status == 3" color="orange">异常未修</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="topRight"
                title="确定要删除此记录吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <SecurityRecordEdit
      v-model:visible="showEdit"
      :data="current"
      @done="reload"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { messageLoading, toDateString } from 'ele-admin-pro/es';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    SecurityRecord,
    SecurityRecordParam
  } from '@/api/tower/security-record/model';
  import {
    pageSecurityRecord,
    removeSecurityRecord
  } from '@/api/tower/security-record';
  import SecurityRecordEdit from './components/security-record-edit.vue';
  import { Project } from '@/api/tower/project/model';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '操作人',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '现场图片',
      dataIndex: 'images',
      key: 'images'
    },
    {
      title: '定位',
      dataIndex: 'longitude',
      key: 'longitude'
    },
    {
      title: '备注说明',
      dataIndex: 'comments',
      key: 'comments'
    },
    {
      title: '完成状态',
      dataIndex: 'status',
      key: 'status',
      width: 180
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      customRender: ({ text }) => toDateString(text)
    }
  ]);

  // 当前编辑数据
  const current = ref<SecurityRecord | null>(null);
  const searchText = ref('');
  const searchStatus = ref('');
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const projectName = ref('');

  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);
  /* 搜索 */
  const onRange = () => {
    const [d1, d2] = dateRange.value ?? [];
    reload({
      createTimeStart: d1 ? d1 + ' 00:00:00' : '',
      createTimeEnd: d2 ? d2 + ' 23:59:59' : ''
    });
  };

  // 表格数据源
  const datasource: DatasourceFunction = ({ where }) => {
    if (searchText.value && searchText.value != '') {
      where.keywords = searchText.value;
    }
    return pageSecurityRecord({ ...where });
  };

  /* 刷新表格 */
  const reload = (where?: SecurityRecordParam) => {
    tableRef?.value?.reload({ where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: SecurityRecord | null, id?: number) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const search = (searchText) => {
    reload({ keywords: searchText });
  };

  const chooseProject = (row: Project) => {
    reload({ projectId: row.projectId });
  };

  const onStatus = (e: any) => {
    console.log(e.target.value);
    const status = e.target.value;
    reload({ status });
  };

  /* 删除单个 */
  const remove = (row: SecurityRecord) => {
    const hide = messageLoading('请求中..', 0);
    removeSecurityRecord(row.securityRecordId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 自定义行属性 */
  const customRow = (record: SecurityRecord) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'TowerSecurityRecord'
  };
</script>
