<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <template #extra>
      <Extra/>
    </template>
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="appId"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
            @remove="removeBatch"
            @batchMove="openMove"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'appIcon'">
            <a-avatar :src="record.appIcon" :size="40"/>
          </template>
          <template v-if="column.key === 'appName'">
            <a-space :size="12">
              <a-tooltip title="查看详情">
                <span class="cursor-pointer" @click="push('/project/detail/' + record.appId)">{{
                    record.appName
                  }}</span>
              </a-tooltip>
              <StarOutlined :style="record.collection ? 'color: #f56a00' : 'color: #e5e7eb'"
                            @click="onCollection(record)"/>
            </a-space>
          </template>
          <template v-if="column.key === 'appType'">
            <span class="cursor-pointer"
                   @click="openUrl(`https://${record.adminUrl}/login?loginPhone=${record.superAdminPhone}`)">
              <a-tooltip title="跳转后台登录">
                {{ record.appType }}
              </a-tooltip>
            </span>
          </template>
          <template v-if="column.key === 'appUrl'">
            <template v-if="record.appUrl">
              <a-tooltip title="访问PC版">
                <DesktopOutlined class="text-xl" @click="openUrl(`http://${record.appUrl}`)"/>
              </a-tooltip>
              <a-divider type="vertical"/>
              <a-tooltip title="访问移动版">
                <MobileOutlined class="text-xl" @click="onShare(record)"/>
              </a-tooltip>
            </template>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 0" color="green">显示</a-tag>
            <a-tag v-if="record.status === 1" color="red">隐藏</a-tag>
          </template>
          <template v-if="column.key === 'recommend'">
            <a-space @click="onRecommend(record)">
              <span v-if="record.recommend === 1" class="ele-text-success"
              ><CheckOutlined
              /></span>
              <span v-else class="ele-text-placeholder"><CloseOutlined/></span>
            </a-space>
          </template>
          <template v-if="column.key === 'appStatus'">
            <a-tag v-if="record.appStatus === '开发中'" color="red">开发中</a-tag>
            <a-tag v-if="record.appStatus === '已上架'" color="success">运行中</a-tag>
            <a-tag v-if="record.appStatus === '维护中'" color="orange"></a-tag>
            <a-tag v-if="record.appStatus === '已下架'">已下线</a-tag>
            <a-tag v-if="!record.appStatus">未分配</a-tag>
          </template>
          <template v-if="column.key === 'progress'">
            <div class="w-full flex justify-center">
              <div class="w-24">
                <a-progress :percent="record.progress" size="small"/>
              </div>
            </div>
          </template>
          <template v-if="column.key === 'nickname'">
            <span>{{ record.nickname || '未分配' }}</span>
          </template>
          <template v-if="column.key === 'projectUsers'">
            <a-avatar-group :max-count="3" :max-style="{ color: '#f56a00', backgroundColor: '#fde3cf' }">
              <template v-for="item in record.projectUsers">
                <a-tooltip :title="item.nickname" placement="top">
                  <a-avatar :src="item.avatar"/>
                </a-tooltip>
              </template>
            </a-avatar-group>
          </template>
          <template v-if="column.key === 'expirationTime'">
            <div>{{ toDateString(record.createTime, 'yyyy-MM-dd') }}</div>
            <div @click="openExpirationTimeEdit(record)">{{ toDateString(record.expirationTime, 'yyyy-MM-dd') }}</div>
            <template v-if="sceneType == 'totalPrice30'">
              <span class="text-purple-500">剩余 {{ record.expiredDays }} 天</span>
            </template>
            <template v-else-if="record.expired < 0 || sceneType == 'Expired'">
              <span class="text-red-500">已过期 {{ record.expiredDays }} 天</span>
            </template>
            <template v-else>
              <span class="text-gray-400">剩余 {{ record.expiredDays }} 天</span>
            </template>
          </template>
          <template v-if="column.key === 'action'">
            <a @click="push('/project/detail/' + record.appId)">详情</a>
            <a-divider type="vertical"/>
            <a @click="openEdit(record)">修改</a>
            <a-divider type="vertical"/>
            <a-popconfirm
              title="确定要删除此记录吗？"
              @confirm="remove(record)"
            >
              <a class="ele-text-danger">删除</a>
            </a-popconfirm>
          </template>
        </template>
      </ele-pro-table>
    </a-card>


    <!-- 编辑弹窗 -->
    <ProjectEdit v-model:visible="showEdit" :data="current" @done="reload"/>

    <!-- 二维码 -->
    <Qrcode v-model:visible="showQrcode" :data="`${qrcode}`" @done="hideShare"/>

    <!-- 修复到期时间 -->
    <ExpirationTimeEdit v-model:visible="showExpirationTimeEdit" :data="current" @done="reload"/>
  </a-page-header>
</template>

<script lang="ts" setup>
import {createVNode, ref} from 'vue';
import {message, Modal} from 'ant-design-vue';
import {
  ExclamationCircleOutlined,
  CheckOutlined,
  CloseOutlined,
  StarOutlined,
  MobileOutlined,
  DesktopOutlined
} from '@ant-design/icons-vue';
import type {EleProTable} from 'ele-admin-pro';
import {toDateString} from 'ele-admin-pro';
import type {
  DatasourceFunction,
  ColumnItem
} from 'ele-admin-pro/es/ele-pro-table/types';
import Search from './components/search.vue';
import ProjectEdit from './components/projectEdit.vue';
import {pageProject, removeProject, removeBatchProject} from '@/api/project/project';
import type {Project, ProjectParam} from '@/api/project/project/model';
import {getPageTitle, openUrl, push} from "@/utils/common";
import Extra from "./components/extra.vue";
import {updateProject} from "@/api/project/project";
import {addProjectCollection, getProjectCollection, removeProjectCollection} from "@/api/project/projectCollection";
import Qrcode from "@/components/QrCode/index.vue";
import {hasRole} from "@/utils/permission";
import ExpirationTimeEdit from "@/views/project/projectRenew/components/expirationTimeEdit.vue";

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

// 表格选中数据
const selection = ref<Project[]>([]);
// 当前编辑数据
const current = ref<Project | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示批量移动弹窗
const showMove = ref(false);
// 是否显示续费时间修复弹窗
const showExpirationTimeEdit = ref(false);
// 加载状态
const loading = ref(true);
// 是否显示二维码
const showQrcode = ref(false);
// 二维码内容
const qrcode = ref();

// 表格数据源
const datasource: DatasourceFunction = ({
                                          page,
                                          limit,
                                          where,
                                          orders,
                                          filters
                                        }) => {
  if (filters) {
    where.status = filters.status;
  }
  return pageProject({
    ...where,
    ...orders,
    page,
    limit
  });
};

// 表格列配置
const columns = ref<ColumnItem[]>([
  // {
  //   title: 'ID',
  //   dataIndex: 'appId',
  //   key: 'appId',
  //   align: 'center',
  //   width: 90,
  // },
  {
    title: 'LOGO',
    dataIndex: 'appIcon',
    key: 'appIcon',
    align: 'center',
    width: 120
  },
  {
    title: '项目名称',
    dataIndex: 'appName',
    key: 'appName',
    width: 280
  },
  {
    title: '产品',
    dataIndex: 'appType',
    key: 'appType',
    align: 'center'
  },
  {
    title: '访问域名',
    dataIndex: 'appUrl',
    key: 'appUrl',
    align: 'center'
  },
  {
    title: '项目代码',
    dataIndex: 'appCode',
    key: 'appCode',
    hideInTable: true,
    align: 'center'
  },
  {
    title: '包名',
    dataIndex: 'packageName',
    key: 'packageName',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'comments',
    key: 'comments',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '开发者',
    dataIndex: 'developer',
    key: 'developer',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '项目负责人',
    dataIndex: 'director',
    key: 'director',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '定价',
    dataIndex: 'price',
    key: 'price',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '评分',
    dataIndex: 'score',
    key: 'score',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '星级',
    dataIndex: 'star',
    key: 'star',
    align: 'center',
    hideInTable: true,
  },
  {
    title: '版本',
    dataIndex: 'edition',
    key: 'edition',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '续费提醒',
    dataIndex: 'showExpiration',
    key: 'showExpiration',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '案例',
    dataIndex: 'showCase',
    key: 'showCase',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '首页',
    dataIndex: 'showIndex',
    key: 'showIndex',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '过期状态',
    dataIndex: 'soon',
    key: 'soon',
    hideInTable: true,
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    hideInTable: true,
    align: 'center',
  },
  // {
  //   title: '推荐',
  //   dataIndex: 'recommend',
  //   key: 'recommend',
  //   align: 'center',
  // },
  {
    title: '项目成员',
    dataIndex: 'projectUsers',
    key: 'projectUsers',
    align: 'center'
  },
  {
    title: '开发进度',
    dataIndex: 'progress',
    key: 'progress',
    width: 180,
    align: 'center'
  },
  {
    title: '开发状态',
    dataIndex: 'appStatus',
    key: 'appStatus',
    width: 120,
    align: 'center',
  },
  {
    title: '排序',
    dataIndex: 'sortNumber',
    key: 'sortNumber',
    align: 'center',
    width: 90
  },
  // {
  //   title: '到期时间',
  //   dataIndex: 'expirationTime',
  //   key: 'expirationTime',
  //   align: 'center',
  //   sorter: true,
  //   ellipsis: true,
  //   width: 150,
  //   customRender: ({text}) => toDateString(text, 'yyyy-MM-dd')
  // },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
    hideInSetting: true
  }
]);

/* 搜索 */
const reload = (where?: ProjectParam) => {
  selection.value = [];
  tableRef?.value?.reload({where: where});
};

const onRecommend = (row: Project) => {
  updateProject({
    ...row,
    recommend: row.recommend == 1 ? 0 : 1
  }).then((msg) => {
    message.success(msg);
    reload();
  });
};

/* 打开续费修复弹窗 */
const openExpirationTimeEdit = (row: Project) => {
  // 非财务人员不能修改
  if (!hasRole('superAdmin')) {
    return false;
  }
  current.value = row;
  showExpirationTimeEdit.value = true;
};

// 加入我的收藏
const onCollection = (item: Project) => {
  // 是否已收藏
  getProjectCollection(item.appId).then((data) => {
    if (data) {
      item.collection = true;
      removeProjectCollection(item.appId).then(msg => {
        message.success(msg);
      })
    } else {
      addProjectCollection({
        appId: item.appId
      }).then((msg) => {
        message.success(msg);
      })
    }
    reload()
  }).catch(err => {
    console.log(err)
  });
}

const onShare = (row?: Project) => {
  qrcode.value = `https://${row?.appUrl}`
  showQrcode.value = true;
}

const hideShare = () => {
  showQrcode.value = false;
}

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

/* 打开批量移动弹窗 */
const openMove = () => {
  showMove.value = true;
};

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

/* 批量删除 */
const removeBatch = () => {
  if (!selection.value.length) {
    message.error('请至少选择一条数据');
    return;
  }
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的记录吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: () => {
      const hide = message.loading('请求中..', 0);
      removeBatchProject(selection.value.map((d) => d.appId))
        .then((msg) => {
          hide();
          message.success(msg);
          reload();
        })
        .catch((e) => {
          hide();
          message.error(e.message);
        });
    }
  });
};

/* 查询 */
const query = () => {
  loading.value = true;
};

/* 自定义行属性 */
const customRow = (record: Project) => {
  return {
    // 行点击事件
    onClick: () => {
      // push('/project/detail/' + record.appId);
    },
    // 行双击事件
    onDblclick: () => {
      // push('/project/detail/' + record.appId);
      openEdit(record);
    }
  };
};
query();
</script>

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

<style lang="less" scoped></style>
