<template>
  <div class="guns-layout-content">
    <div class="guns-layout">
      <div class="guns-layout-content-application">
        <div class="content-mian">
          <a-spin :delay="100" :spinning="loading">
            <div class="content-mian-header">
              <div class="header-content" style="justify-content: space-between">
                <div class="header-content-left1">
                  <a-space>
                    <a-input v-model:value="where.searchText" placeholder="流程名称" @pressEnter="reload" v-if="!isShowFlowControl">
                      <template #prefix>
                        <icon-font iconClass="icon-opt-search"></icon-font>
                      </template>
                    </a-input>
                    <a-input
                      v-model:value="where.applicantName"
                      placeholder="流程发起人"
                      class="search-input"
                      @focus="userOrDeptSelect('user')"
                      v-if="!isShowFlowControl && selectMenu != 60"
                    />
                    <a-input
                      v-model:value="where.applicantOrgName"
                      placeholder="发起人部门"
                      class="search-input"
                      @focus="userOrDeptSelect('dept')"
                      v-if="!isShowFlowControl && selectMenu != 60"
                    />
                    <a-select
                      v-model:value="where.instanceStatus"
                      placeholder="请选择"
                      class="search-input"
                      allowClear
                      v-if="!isShowFlowControl && selectMenu != 60"
                    >
                      <a-select-option :value="20">处理中</a-select-option>
                      <a-select-option :value="30">已完成</a-select-option>
                      <a-select-option :value="40">已拒绝</a-select-option>
                      <a-select-option :value="50">挂起</a-select-option>
                      <a-select-option :value="60">作废</a-select-option>
                    </a-select>
                    <a-date-picker
                      class="search-input"
                      v-model:value="where.searchBeginTime"
                      value-format="YYYY-MM-DD"
                      placeholder="流程发起日期"
                      v-if="!isShowFlowControl && selectMenu != 60"
                    />

                    <a-button class="border-radius" v-if="!isShowFlowControl && selectMenu != 60" @click="clearAll">清空</a-button>
                    <a-button type="primary" class="border-radius" v-if="!isShowFlowControl && selectMenu != 60" @click="reload"
                      >搜索</a-button
                    >

                    <a-button
                      style="background-color: rgba(67, 207, 124, 1); color: #fff; border-radius: 5px"
                      @click="betch"
                      v-if="isShowFlowControl"
                      >已阅</a-button
                    >
                  </a-space>
                </div>
                <div class="header-content-right1">
                  <a-space>
                    <a-button
                      class="list-button border-radius"
                      type="primary"
                      @click="flowControl"
                      v-if="!isShowFlowControl && props.selectMenu == 20"
                      >批量处理</a-button
                    >
                    <a-button class="list-button border-radius" type="primary" v-if="isShowFlowControl" @click="backTable">返回</a-button>
                  </a-space>
                </div>
              </div>
            </div>
            <div class="content-mian-body">
              <div class="table-content" v-if="flowList && flowList.length > 0">
                <div class="list-box-table">
                  <a-checkbox-group v-model:value="flowListSelect" style="width: 100%">
                    <div class="list-item" v-for="(flowItem, flowIndex) in flowList" :key="flowIndex">
                      <a-checkbox :value="flowItem" class="list-item-checkbox" v-show="isShowFlowControl"></a-checkbox>
                      <div class="list-item-content" :style="{ width: isShowFlowControl ? 'calc(100% - 30px)' : '100%' }">
                        <!-- 头部 -->
                        <div class="list-item-content-header">
                          <div class="list-item-content-header-top">
                            <div class="list-item-content-header-top-left">
                              <img :src="flowItem.applicantWrapper.avatarUrl" alt="" class="list-item-content-header-top-left-img" />
                              <div class="list-item-content-header-top-left-content">
                                <div class="list-item-content-header-top-left-content-top">
                                  <a-popover placement="topLeft">
                                    <template #content>
                                      <p><span class="popover-title">所属流程：</span>{{ flowItem?.definitionIdWrapper?.modelName }}</p>
                                      <p>
                                        <span class="popover-title">版本号：</span>{{ flowItem?.definitionIdWrapper?.definitionVersion }}
                                      </p>
                                    </template>
                                    <span @click="flowItemClick(flowItem)" class="list-item-content-header-top-left-title ellipsis">{{
                                      flowItem.instanceTitle
                                    }}</span>
                                  </a-popover>
                                  <InstanceStatusTag :record="flowItem" v-if="props.selectMenu != 60" />
                                </div>
                                <div class="list-item-content-header-top-left-content-bottom">
                                  <div class="ellipsis">
                                    <span>{{ flowItem.applicantWrapper?.realName }}</span>
                                    <span v-if="flowItem.applicantOrgIdWrapper"
                                      >（{{ flowItem?.applicantOrgIdWrapper }}
                                      <span v-if="!flowItem.applicantPositionIdWrapper">）</span></span
                                    >
                                    <span v-if="flowItem.applicantPositionIdWrapper">/{{ flowItem?.applicantPositionIdWrapper }}）</span>
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div class="list-item-content-header-top-right" v-if="props.selectMenu != 60">
                              <div class="list-item-content-header-top-right-top">
                                <a-space :size="12">
                                  <span class="list-item-content-header-top-right-top-item" @click="tagManage(flowItem, flowIndex)">
                                    <img src="@/assets/images/biaoqian.svg" alt="" />
                                    <span>标签</span>
                                  </span>
                                  <span class="list-item-content-header-top-right-top-item" @click="remarkManage(flowItem, flowIndex)">
                                    <img src="@/assets/images/beizhu.svg" alt="" />
                                    <a-badge dot v-if="flowItem?.remarkList?.length > 0">
                                      <span>备注</span>
                                    </a-badge>
                                    <span v-else>备注</span>
                                  </span>
                                  <span class="list-item-content-header-top-right-top-item" v-if="flowItem?.instanceId">
                                    <a-popover placement="bottomRight" trigger="click" v-model:visible="flowItem.useVisible">
                                      <template #content>
                                        <div class="use-item" @click="exportInfo(flowItem)">导出工作信息</div>
                                      </template>
                                      <span @click="useClick(flowItem)">
                                        <setting-outlined />
                                        <span>功能</span>
                                      </span>
                                    </a-popover>
                                  </span>
                                </a-space>
                              </div>
                              <div class="list-item-content-header-top-right-bottom">
                                <a-space :size="4">
                                  <a-tooltip
                                    placement="bottom"
                                    :overlayClassName="getClassNameAndBgColor(flowItem, tagIndex).className"
                                    v-for="tagIndex in [0, 1, 2, 3, 4]"
                                    :key="tagIndex"
                                  >
                                    <template #title v-if="getClassNameAndBgColor(flowItem, tagIndex).tagName">
                                      {{ getClassNameAndBgColor(flowItem, tagIndex).tagName }}
                                    </template>
                                    <span
                                      class="list-item-content-header-top-right-bottom-item"
                                      :style="{ backgroundColor: getClassNameAndBgColor(flowItem, tagIndex).bgColor }"
                                    ></span>
                                  </a-tooltip>
                                </a-space>
                              </div>
                            </div>
                          </div>
                          <div class="list-item-content-header-bottom">
                            <div
                              class="list-item-content-header-item ellipsis"
                              v-for="(sItem, sIndex) in flowItem.summaryFieldValueList"
                              :key="sIndex"
                              :style="{ borderRight: flowItem.summaryFieldValueList?.length > 2 ? '1px solid #ccc' : '' }"
                            >
                              <span class="list-item-content-header-item-title">{{ sItem?.summaryFieldName }}：</span>
                              {{ sItem?.summaryFieldValue }}
                            </div>
                          </div>
                        </div>
                        <!-- 线 -->
                        <div class="list-item-content-line"></div>
                        <!-- 尾部 -->
                        <div class="list-item-content-body">
                          <div class="list-item-content-body-left">
                            <a-space>
                              <field-time-outlined />
                              <span v-if="flowItem.currentRuntimeNodeList && props.selectMenu != 60"
                                >{{ getCurrentRuntimeNodeList(flowItem.currentRuntimeNodeList) }}：
                                <span v-if="props.selectMenu != 60">
                                  {{ getCurrentApproverListWrapper(flowItem.currentApproverListWrapper) }}</span
                                >
                              </span>

                              <span v-if="props.selectMenu == 60">
                                <span>草稿：</span>
                                <span>{{ flowItem.applicantWrapper?.realName }}</span>
                              </span>
                            </a-space>
                          </div>
                          <div class="list-item-content-body-right">
                            {{ flowItem?.createTime }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </a-checkbox-group>
                </div>
                <a-pagination
                  :current="pageNo"
                  :page-size="pageSize"
                  :total="total"
                  size="small"
                  class="pagination"
                  v-if="total > 0"
                  show-size-changer
                  show-quick-jumper
                  @change="pageSizeChange"
                  @showSizeChange="showSizeChange"
                  :show-total="total => `共${total}条`"
                />
              </div>
              <a-empty class="content-empty" v-else />
            </div>
          </a-spin>
        </div>
      </div>
    </div>

    <!-- 流程同意弹框 -->
    <AgreeOperate v-model:visible="isShowAgree" v-if="isShowAgree" :data="flowListSelect" @done="getFlowList" />

    <!-- 详情 -->
    <WorkflowTaskDetail
      v-model:visible="isShowEdit"
      v-if="isShowEdit"
      :data="current"
      @done="getFlowList"
      :taskCondition="props.selectMenu"
    />

    <!-- 选择组件 -->
    <Selection
      v-model:visible="visibleFlowPick"
      v-if="visibleFlowPick"
      :data="selectedData"
      :showTab="showTab"
      :isRadio="isRadio"
      @done="closeFlowPick"
    ></Selection>

    <!-- 标签管理 -->
    <TagManage v-model:visible="showTagManage" v-if="showTagManage" :data="current" @done="closeTagManage" />
    <!-- 备注管理 -->
    <RemarkManage v-model:visible="showRemarkManage" v-if="showRemarkManage" :data="current" @done="closeRemarkManage" />
  </div>
</template>

<script setup name="WorkflowTaskTable">
import { message } from 'ant-design-vue/es';
import { ref, onMounted, watch } from 'vue';
import { FlowTaskApi } from '../api/FlowTaskApi';
import AgreeOperate from './operate/agree-operate.vue';
import WorkflowTaskDetail from './task-detail.vue';
import InstanceStatusTag from './detail/instance-status-tag.vue';
import { deepClone } from '@/utils/common/util';
import TagManage from './operate/tag-manage.vue';
import RemarkManage from './operate/remark-manage.vue';

const props = defineProps({
  // 选中类型
  selectMenu: {
    type: Number,
    default: 10
  },
  // 任务id
  taskId: {
    type: String,
    default: ''
  },
  // 实例id
  instanceId: {
    type: String,
    default: ''
  }
});

const emits = defineEmits(['draft', 'changeNumber']);
// 查询条件
const where = ref({
  searchText: '',
  applicant: [],
  applicantOrgId: '',
  instanceStatus: null,
  searchBeginTime: ''
});

// 流程任务列表
const flowList = ref([]);

// 当前所在页数
const pageNo = ref(1);
// 当前分页条数
const pageSize = ref(10);
// 总数据
const total = ref(0);

// 加载状态
const loading = ref(false);

// 选中列表
const flowListSelect = ref([]);

// 是否显示多选框
const isShowFlowControl = ref(false);

// 是否显示同意弹框
const isShowAgree = ref(false);
// 是否显示详情弹框
const isShowEdit = ref(false);

// 当前行数据
const current = ref(null);

// 当前行索引
const currentIndex = ref(0);

// 是否显示选择弹框
const visibleFlowPick = ref(false);
// 选择总数据
const selectedData = ref({
  selectUserList: [],
  selectOrgList: []
});

// 选择类型
const showTab = ref(['user']);

// 是否是初始化
const isInit = ref(true);

const isRadio = ref(true);

// 是否显示标签管理
const showTagManage = ref(false);
// 是否显示备注管理
const showRemarkManage = ref(false);

// 重新加载
const reload = () => {
  getFlowList(false);
};

// 清空搜索条件
const clearAll = () => {
  where.value = {};
  reload();
};

onMounted(() => {
  getFlowList(false);
});

watch(
  () => props.selectMenu,
  val => {
    if (val) {
      flowList.value = [];
      total.value = 0;
      pageNo.value = 1;
      pageSize.value = 10;
      flowListSelect.value = [];
      getFlowList();
    }
  }
);

// 获取流程任务列表
const getFlowList = (flag = true) => {
  loading.value = true;
  let params = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    taskCondition: props.selectMenu,
    ...where.value
  };
  let result;
  if (props.selectMenu != 60) {
    result = FlowTaskApi.getUserTasksRuTask(params);
    if (flag && (props.selectMenu == 10 || props.selectMenu == 20)) {
      emits('changeNumber');
    }
  } else if (props.selectMenu == 60) {
    result = FlowTaskApi.flowEngineDraftPage(params);
  }
  result
    .then(async res => {
      if (res.code == '00000') {
        if (props.selectMenu == params.taskCondition) {
          let arr = res.data.rows ?? [];
          flowList.value = arr?.map(item => {
            return { ...item, useVisible: false };
          });
          total.value = res.data.totalRows;
          flowListSelect.value = [];
          if (props.taskId && props.instanceId && isInit.value) {
            let parmastwo = deepClone(params);
            parmastwo.taskId = props.taskId;
            const res = await FlowTaskApi.getUserTasksRuTask(parmastwo);
            if (res.data.rows?.length > 0) {
              current.value = res.data.rows[0];
              isShowEdit.value = true;
            }
            isInit.value = false;
          }
        }
      }
    })
    .finally(() => (loading.value = false));
};

// 分页的页数改变
const pageSizeChange = (page, pageSize) => {
  pageNo.value = page;
  getFlowList();
};

// 条数改变
const showSizeChange = (current, size) => {
  pageSize.value = size;
  getFlowList();
};

// 流程点击
const flowItemClick = flowItem => {
  if (props.selectMenu == 60) {
    emits('draft', flowItem);
  } else {
    current.value = flowItem;
    isShowEdit.value = true;
  }
};

// 批量处理按钮点击
const flowControl = () => {
  isShowFlowControl.value = true;
};

// 返回列表
const backTable = () => {
  isShowFlowControl.value = false;
  flowListSelect.value = [];
};

// 批量处理
const betch = () => {
  if (props.selectMenu == 10) {
    agreeFlow();
  } else if (props.selectMenu == 20) {
    // 待阅任务
    readFlow();
  }
};

// 同意流程
const agreeFlow = () => {
  if (flowListSelect.value.length == 0) return message.warning('请选择一条数据');
  isShowAgree.value = true;
};

// 已阅
const readFlow = () => {
  if (flowListSelect.value.length == 0) return message.warning('请选择一条数据');
  let taskIdList = flowListSelect.value.map(item => item.id);
  FlowTaskApi.batchRead({ taskIdList: taskIdList }).then(res => {
    if (res.code == '00000') {
      message.success(res.message);
      getFlowList();
    }
  });
};

// 用户、部门选择
const userOrDeptSelect = type => {
  isRadio.value = type == 'user' ? false : true;
  showTab.value = [type];
  visibleFlowPick.value = true;
};

// 关闭选择弹框
const closeFlowPick = data => {
  if (showTab.value[0] == 'user') {
    where.value.applicant = data.selectUserList.map(item => item.bizId);
    where.value.applicantName = data.selectUserList.map(item => item.name).join(';');
  } else {
    const { bizId, name } = data.selectOrgList[0] || { bizId: '', name: '' };
    where.value.applicantOrgId = bizId;
    where.value.applicantOrgName = name;
  }
};

// 设置当前办理节点
const getCurrentRuntimeNodeList = list => {
  let name = '';
  if (list?.length > 0) {
    name = list.map(item => item.nodeName).join(';');
  }
  return name;
};
// 设置当前办理人
const getCurrentApproverListWrapper = list => {
  let name = '';
  if (list?.length > 0) {
    name = list.map(item => item.realName).join(';');
  }
  return name;
};

// 获取样式名称和背景色
const getClassNameAndBgColor = (item, index) => {
  const tagColorClassMap = {
    '#ff453b': 'label-red',
    '#ff823b': 'label-orange',
    '#ffd03b': 'label-yellow',
    '#151aff': 'label-blue',
    '#1bb854': 'label-green'
  };

  let obj = {
    className: '',
    bgColor: '',
    tagName: ''
  };

  if (item?.tagList?.[index]) {
    const tag = item.tagList[index];
    obj.bgColor = tag.tagColor;
    obj.tagName = tag.tagName;
    obj.className = tagColorClassMap[tag.tagColor] || '';
  }

  return obj;
};

// 标签管理
const tagManage = (item, index) => {
  current.value = item;
  currentIndex.value = index;
  showTagManage.value = true;
};

// 关闭标签列表
const closeTagManage = list => {
  flowList.value[currentIndex.value].tagList = list;
};

// 备注管理
const remarkManage = (item, index) => {
  current.value = item;
  currentIndex.value = index;
  showRemarkManage.value = true;
};

// 关闭备注管理
const closeRemarkManage = list => {
  flowList.value[currentIndex.value].remarkList = list;
};

// 导出信息
const exportInfo = async item => {
  await FlowTaskApi.exportExcel({ instanceId: item.instanceId });
  item.useVisible = false;
};

// 功能点击
const useClick = flowItem => {
  flowItem.useVisible = !flowItem.useVisible;
};
</script>

<style lang="less">
.label-red {
  .ant-tooltip-inner {
    border: 1px solid #ff453b;
    background-color: #fff;
    color: #ff453b;
    padding: 4px 12px;
  }

  .ant-tooltip-arrow-content {
    border: 1px solid #ff453b;
    background-color: #fff;
  }
}

.label-orange {
  .ant-tooltip-inner {
    border: 1px solid #ff823b;
    background-color: #fff;
    color: #ff823b;
    padding: 4px 12px;
  }

  .ant-tooltip-arrow-content {
    border: 1px solid #ff823b;
    background-color: #fff;
  }
}
.label-yellow {
  .ant-tooltip-inner {
    border: 1px solid #ffd03b;
    background-color: #fff;
    color: #ffd03b;
    padding: 4px 12px;
  }

  .ant-tooltip-arrow-content {
    border: 1px solid #ffd03b;
    background-color: #fff;
  }
}
.label-blue {
  .ant-tooltip-inner {
    border: 1px solid #151aff;
    background-color: #fff;
    color: #151aff;
    padding: 4px 12px;
  }

  .ant-tooltip-arrow-content {
    border: 1px solid #151aff;
    background-color: #fff;
  }
}
.label-green {
  .ant-tooltip-inner {
    border: 1px solid #1bb854;
    background-color: #fff;
    color: #1bb854;
    padding: 4px 12px;
  }

  .ant-tooltip-arrow-content {
    border: 1px solid #1bb854;
    background-color: #fff;
  }
}
</style>

<style scoped lang="less">
.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.guns-layout-content {
  width: 100%;
  height: 100%;
  padding: 20px 12px 12px 12px;
}
.header-content {
  margin-bottom: 20px !important;
}
.content-mian-body {
  position: relative;
}
.search-input {
  height: 36px;
  width: 150px !important;
  :deep(.ant-select-selection-placeholder) {
    line-height: 36px !important;
  }
  :deep(.ant-select-selector) {
    height: 100% !important;
  }
  :deep(.ant-select-selection-item) {
    line-height: 36px;
  }
}
.content-empty {
  position: absolute;
  top: 30%;
  left: 50%;
  margin-left: -92px;
}
:deep(.ant-spin-container) {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.list-box-table {
  height: calc(100% - 40px);
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}
.content-mian {
  min-width: 1080px;
}
.pagination {
  margin-top: 10px;
  height: 30px;
  text-align: right;
}
.content-mian-body {
  overflow: hidden;
}
.table-content {
  overflow-y: auto;
}
.ant-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}
.list-item {
  margin: 0 2px;
  width: calc(50% - 11px);
  position: relative;
  display: flex;
  &:nth-child(1) {
    margin-top: 1px;
  }

  &:nth-child(2n) {
    margin-left: 14px;
  }

  .list-item-content {
    padding: 12px 16px;
    border: 1px solid rgba(197, 207, 209, 0.4);
    box-shadow: 0 0 2px rgba(197, 207, 209, 0.4);
    margin: 0 0px 16px 0px;
    border-radius: 8px;

    .list-item-content-header {
      width: 100%;
      position: relative;

      .list-item-content-header-top {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        font-size: 16px;
        font-style: normal;
        .list-item-content-header-top-left {
          width: calc(100% - 170px);
          color: #43505e;
          font-weight: 500;

          display: flex;
          align-items: center;

          .list-item-content-header-top-left-img {
            width: 40px;
            height: 40px;
            margin-right: 12px;
            border-radius: 50%;
          }
          .list-item-content-header-top-left-content {
            width: calc(100% - 52px);

            .list-item-content-header-top-left-content-top {
              width: 100%;
              display: flex;
              align-items: center;
            }

            .list-item-content-header-top-left-content-bottom {
              width: 100%;
              font-size: 12px;
              color: #898e91;
              font-weight: 400;
            }
          }
          .list-item-content-header-top-left-title {
            display: inline-block;
            max-width: calc(100% - 90px);
            margin-right: 10px;
            font-weight: 600;
            color: #43505e;
          }
          span {
            cursor: pointer;
            &:hover {
              text-decoration: underline;
              color: var(--primary-color);
            }
          }
        }
        .list-item-content-header-top-right {
          text-align: right;
          width: 170px;
          color: #898e91;
          font-size: 14px;
          font-style: normal;
          font-weight: 400;

          .list-item-content-header-top-right-top-item {
            display: flex;
            align-items: center;
            cursor: pointer;

            span {
              font-size: 12px;
              color: #60666b;
              margin-left: 2px;
            }
          }

          .list-item-content-header-top-right-bottom {
            margin-top: 10px;
            display: flex;
            justify-content: end;

            .list-item-content-header-top-right-bottom-item {
              cursor: pointer;
              width: 8px;
              height: 8px;
              display: block;
              border-radius: 2px;
              background-color: rgba(168, 174, 175, 0.4);
            }
          }
        }
      }
      .list-item-content-header-bottom {
        margin-left: 52px;
        width: calc(100% - 52px);
        height: 44px;
        display: flex;
        flex-wrap: wrap;

        .list-item-content-header-item {
          width: calc(50% - 5px);

          &:nth-child(2n) {
            margin-left: 10px;
            border-color: #fff !important;
          }

          .list-item-content-header-item-title {
            color: #898e91;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
          }
        }
      }
    }
    .list-item-content-line {
      width: 100%;
      height: 0.5px;
      background-color: rgba(197, 207, 209, 0.4);
      margin: 12px 0;
    }

    .list-item-content-body {
      height: 20px;
      line-height: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .list-item-content-body-left {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #60666b;
      }

      .list-item-content-body-right {
        color: #898e91;
        font-size: 12px;
      }
    }
  }

  .list-item-checkbox {
    margin-right: 20px;
    width: 10px;
    height: 120px;
    line-height: 120px;
  }
}
.popover-title {
  color: #898e91;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
}

.use-item {
  width: 100%;
  cursor: pointer;
}
</style>
