<template>
  <div class="card-search">
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="formState"
      @finish="onFinish"
    >
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item
            name="tempName"
            label="模板名称"
            :label-col="{span:6}">
            <a-input v-model:value="formState.tempName" style="width: 200px"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item
            name="tempNo"
            label="模板编号"
            :label-col="{span:6}">
            <a-input v-model:value="formState.tempNo" style="width: 200px"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item
            name="tempNo"
            label="创建日期"
            :label-col="{span:6}">
            <a-range-picker format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" @change="onRangeChange"/>
          </a-form-item>
        </a-col>
        <a-col :span="6" style="text-align: left">
          <a-button type="primary" html-type="submit" @click="onFinish">查询</a-button>
          <a-button style="margin: 0 8px" @click="() => {formRef.resetFields();loadData()}">重置</a-button>
        </a-col>
      </a-row>
      <a-row class="edit-operation">
        <a-col :span="24" style="text-align: right">
          <a-radio-group v-model:value="viewModel" style="text-align: left">
            <a-radio-button value="list">
              <UnorderedListOutlined/>
              列表
            </a-radio-button>
            <a-radio-button value="card">
              <TableOutlined/>
              卡片
            </a-radio-button>
          </a-radio-group>
          <a-button type="primary" html-type="button" @click="add">
            <template #icon>
              <PlusOutlined/>
            </template>
            添加搜索模板
          </a-button>
          <a-popconfirm placement="leftTop"
                        title="是否删除模板?"
                        @confirm="onDelete()">
            <a-button type="primary" style="margin: 0 8px" html-type="button">删除</a-button>
          </a-popconfirm>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list" v-if="viewModel=='card'">
      <a-spin :spinning="loading">
        <a-row :gutter="[24,8]">
          <a-col :span="6" v-for="item in data">
            <a-card :title="item.tempName">
              <template #extra>
                <a-button type="link" @click="edit(item.tempId)">查看详情</a-button>
              </template>
              <template class="ant-card-actions" #actions>
                <FormOutlined key="edit" @click="edit(item.tempId)" title="编辑"/>
                <a-popconfirm placement="leftTop"
                              title="是否删除数据?"
                              @confirm="deleteSingle(item.tempId)">
                  <DeleteOutlined key="ellipsis" title="删除"/>
                </a-popconfirm>
                <CloudDownloadOutlined key="edit" @click="down(item.tempId)" title="申请下载"/>
                <CopyOutlined  key="copy" @click="copy(item.tempId)" title="拷贝"/>
              </template>
              <a-popover title="详细信息" :visible="item.visible">
                <template #content>
                  <p class="tip-detail">维度：{{ item.dimensionName }}</p>
                  <p class="tip-detail">度量：{{ item.measurName }}</p>
                </template>
              </a-popover>
              <a-row :gutter="[24,4]">
                <a-col :span="10" class="col-text">模板编号：</a-col>
                <a-col :span="12" class="col-content">{{ item.tempNo }}</a-col>
                <a-col :span="10" class="col-text">维度：</a-col>
                <a-col :span="12" class="col-content" @mouseover="item.visible=true" @mouseout="item.visible=false">{{ item.dimensionName }}</a-col>
                <a-col :span="10" class="col-text">度量：</a-col>
                <a-col :span="12" class="col-content" @mouseover="item.visible=true" @mouseout="item.visible=false">{{ item.measurName }}</a-col>
                <a-col :span="10" class="col-text">创建人：</a-col>
                <a-col :span="12">{{ item.createdName }}</a-col>
                <a-col :span="10" class="col-text">创建/更新日期：</a-col>
                <a-col :span="12">{{ dayjs(item.createTime ?? item.modifyTime).format('YYYY-MM-DD') }}</a-col>
                <a-col :span="10" class="col-text">备注：</a-col>
                <a-col :span="12" class="col-content">{{ item.remark }}</a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>
    </div>
    <div class="search-result-list" v-else="viewModel=='list'">
      <a-table :columns="columns" :data-source="data" :scroll="{ x:'100%', y: 500 }"
               :loading="loading"
               :pagination="false"
               :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :row-key="record=>record.tempId"
               bordered>
        <template #bodyCell="{ column,record }">
          <template v-if="column.key === 'operation'">
            <a-button type="link" size="small" @click="edit(record.tempId)">编辑</a-button>
            <a-button type="link" size="small" @click="down(record.tempId)">申请下载</a-button>
            <a-popover  trigger="hover" placement="left">
              <template #content>
                <a-button type="link" size="small" @click="copy(record.tempId)">复制模板</a-button><br/>
                <a-button type="link" size="small" @click="edit(record.tempId)">查看详情</a-button><br/>
                <a-popconfirm placement="leftTop"
                              title="是否删除数据?"
                              @confirm="deleteSingle(record.tempId)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
              </template>
              <a-button type="link" size="small">更多</a-button>
            </a-popover>

          </template>
        </template>
      </a-table>
    </div>
    <a-pagination :page-size-options="['5', '20', '30', '40', '50']" show-size-changer
                  v-model:current="pagination.current" :total="pagination.total" style="float: right;margin-top: 10px;"
                  :pageSize="pagination.pageSize" :show-total="total => `共 ${total} 条`"
                  @change="(current)=>handleTableChange({ current: current,pageSize: pagination.pageSize })"
                  @showSizeChange="(current,pageSize)=>handleTableChange({ current: current,pageSize: pageSize })"/>
    <Apply @ok="applyOk" v-model:options="applyOptions"></Apply>
  </div>
</template>

<script lang="ts">
import {reactive, ref, defineComponent, computed} from 'vue';
import type {FormInstance} from 'ant-design-vue';
import type {TableColumnsType, TableProps} from 'ant-design-vue';
import {get, postdel} from '@/api/common';
import {useRoute, useRouter} from "vue-router";
import {useTabsViewStore} from "@/store/modules/tabsView";
import {message} from "ant-design-vue";
import {getPaginationTotalTitle} from "@/utils/common";
import dayjs from "dayjs";
import Apply from '@/components/basic/approve/Apply.vue'

export default defineComponent({
  name: 'tempList',
  components: {Apply},
  setup() {
    const route = useRoute();
    const router = useRouter();
    const expand = ref(false);
    const formRef = ref<FormInstance>();
    const tabsViewStore = useTabsViewStore();
    const selectedRowKeys = ref([]);
    const viewModel = ref("card");
    const formState = reactive({
      page: 1, rows: 10, tempName: '', tempNo: '', tempId: "", beiginDate: '', endDate: '', total: 0, isPostManage: true
    });
    const applyOptions = ref({visible: false, tempId: ""});

    const columns: TableColumnsType = [
      {
        title: '序号',
        width: 60,
        dataIndex: 'index',
        key: 'index',
        align: "center",
        customRender: item => `${formState.rows * (formState.page - 1) + item.index + 1}`
      },
      {title: '模板编号', dataIndex: 'tempNo', key: 'tempNo', width: 180, align: "center"},
      {title: '模板名称', dataIndex: 'tempName', key: '1', width: 300},
      {
        title: '创建时间', dataIndex: 'createTime', key: '2', width: 180, customRender: ({record}) =>
          record.createTime == null ? "" : (dayjs(record.createTime).format('YYYY-MM-DD HH:mm'))
      },
      {
        title: '模板状态', dataIndex: 'status', key: '3', width: 100, align: "center", customRender: ({record}) =>
          record.status == 0 ? "正常" : "禁用"
      },
      {title: '备注', dataIndex: 'remark', key: '4', ellipsis: true},
      {title: '操作', key: 'operation', width: 180, align: "center"},
    ];

    const data = ref([]);
    const pagination = computed(() => ({
      total: formState.total,
      current: formState.page,
      pageSize: formState.rows,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));
    const loading = ref(false);

    const handleTableChange: TableProps['onChange'] = (
      pag: { pageSize: number; current: number },
    ) => {
      formState.page = pag.current;
      formState.rows = pag.pageSize;
      loadData();
    };

    const onFinish = () => {
      loadData();
    }
    const onRangeChange = (dateString) => {
      formState.beiginDate = dateString ? dateString[0].format("YYYY-MM-DD") : '';
      formState.endDate = dateString ? dateString[1].format("YYYY-MM-DD") : '';
      loadData();
    };
    const loadData = async function () {
      loading.value = true;
      const result: any = await get('temp/getList', formState);

      data.value = result.list;
      formState.total = result.total;
      loading.value = false;
    }
    const onDelete = () => {
      if (selectedRowKeys.value.length <= 0) {
        message.warning('请选择需要删除的数据！');
        return false;
      }
      postdel('temp/deletes', selectedRowKeys.value).then(() => {
        loadData();
      })
    };
    const deleteSingle = (id: string) => {
      postdel('temp/deletes', [id]).then(() => {
        loadData();
      })
    }
    const add = () => {
      tabsViewStore.addTabByPath('/query/index', {});
    };
    const edit = (key: string) => {
      tabsViewStore.addTabByPath('/query/index', {tempId: key});
    };
    const copy = (key: string) => {
      tabsViewStore.addTabByPath('/query/index', {tempId: key,iscopy:1});
    };
    const onSelectChange = (keys: any) => {
      selectedRowKeys.value = keys;
    };
    const down = (tempId) => {
      applyOptions.value.tempId = tempId;
      applyOptions.value.visible = true;
    }
    const applyOk = (args) => {
      console.log(args);
    }
    return {
      router,
      route,
      expand,
      formRef, onRangeChange,
      formState, viewModel, dayjs,
      columns, data, loading, selectedRowKeys,
      pagination, down, applyOptions, applyOk,
      handleTableChange,
      onSelectChange,
      onFinish,
      loadData,
      add, deleteSingle,
      edit,copy, onDelete
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    if (history.state.params?.reload)
      this.loadData();
  }
});
</script>
<style lang="less" scoped>
.ant-card-actions {
  margin: 0;
  padding: 0;
  list-style: none;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}
.tip-detail{
  flex-wrap: wrap;
  max-width: 500px;
}
.col-text {
  padding-right: 0px !important;
  text-align: right;
  font-weight: bold;
}

.col-content {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
