<template>
  <div class="btn-box">
    <div class="view-box">
      <a-popover v-model:open="state.show" title="视图" placement="bottom">
        <template #content>
          <div class="column-box">
            <div class="column-item" v-for="(item, index) in state.list" :key="index">
              <div
                :class="state.activeId == item.id ? 'active' : 'title'"
                @click="changeActiveId(item)"
                >{{ item.name }}
                <span v-if="item.code == '0'">（默认）</span>
                <span v-else-if="item.isPublic == IS_PUBLIC.PUBLIC">（公开）</span>
                <span v-else-if="item.isPublic == IS_PUBLIC.PRIVATE">（个人）</span>
              </div>
              <div class="opr" v-if="index != 0">
                <ViewBtn
                  class="right-btn"
                  v-bind="$attrs"
                  :objectId="props.objectId"
                  @refresh="refreshList"
                  btnName="编辑视图"
                  :editData="item"
                >
                  <EditOutlined class="edit-box" />
                </ViewBtn>

                <DeleteOutlined class="delete-box" @click="deleteView(item.id)" />
              </div>
            </div>
            <div class="border"></div>
            <div class="add-box"
              ><ViewBtn
                class="right-btn"
                v-bind="$attrs"
                :objectId="props.objectId"
                @refresh="initList"
                btnName="新增视图"
              >
                <PlusOutlined style="margin-right: 6px" />新增视图
              </ViewBtn></div
            >
          </div>
        </template>
        <div class="view-title">
          <div>{{ state.name }}</div>
          <UpOutlined v-if="state.show" />
          <DownOutlined v-else />
        </div>
      </a-popover>
    </div>
    <div class="view-box">
      <div class="view-title" @click="state.modalShow = true">
        <div>筛选</div>
        <UpOutlined v-if="state.modalShow" />
        <DownOutlined v-else />
      </div>
    </div>
    <div class="fixed-box" v-if="state.modalShow">
      <div class="head-box">
        <div class="head-title">筛选</div>
      </div>
      <div class="content" v-if="state.modalShow">
        <div class="action-table">
          <QuickTable
            ref="QuickTableRef"
            v-if="state.modalShow && state.queryType == QUERY_TYPE.QUICK_SEARCH"
            v-bind="$attrs"
            :configJson="state.configJson"
          />
          <AdvancedTable
            ref="AdvancedTableRef"
            v-if="state.modalShow && state.queryType == QUERY_TYPE.ADVANCED_QUERY"
            v-bind="$attrs"
            :configJson="state.configJson"
            :combinationFormula="state.combinationFormula"
          />
        </div>
      </div>
      <div class="action-btn action-btn-box">
        <a-button class="right-btn" @click="state.modalShow = false">取消</a-button>
        <a-button
          type="primary"
          class="right-btn"
          @click="handleSubmit"
          v-if="state.postData.code != '0'"
          >保存为视图</a-button
        >
        <a-button type="primary" @click="search">查询</a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
  import {
    UpOutlined,
    DownOutlined,
    EditOutlined,
    DeleteOutlined,
    PlusOutlined,
  } from '@ant-design/icons-vue';
  import ViewBtn from './ViewBtn.vue';
  import { getUserViewFormView } from '/@/api/form/view';
  import { FormViewInfoData } from '/@/api/form/view/model';
  import { IS_PUBLIC, QUERY_TYPE } from '/@/enums/formViewEnum';
  import { FormType } from '/@/enums/workflowEnum';
  import { deleteFormView } from '/@/api/form/view';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { updateFormView } from '/@/api/form/view';
  const QuickTable = defineAsyncComponent(() => import('./QuickTable.vue'));
  const AdvancedTable = defineAsyncComponent(() => import('./AdvancedTable.vue'));
  const AdvancedTableRef = ref();
  const QuickTableRef = ref();
  const { notification } = useMessage();
  const { t } = useI18n();
  const state = reactive({
    showConfig: true,
    name: '全部（默认）',
    show: false,
    activeId: '0',
    list: [] as Array<FormViewInfoData>,
    modalShow: false,
    configJson: '',
    combinationFormula: '',
    queryType: QUERY_TYPE.QUICK_SEARCH,
    postData: {
      isPublic: IS_PUBLIC.PRIVATE,
      id: '',
      code: '0',
      name: '',
      formViewType: FormType.CUSTOM, //表单类型
      configJson: '',
      combinationFormula: '',
      objectId: '', //系统表单formId,自定义表单releaseId的id值
      queryType: QUERY_TYPE.QUICK_SEARCH,
    },
  });
  const props = defineProps({
    objectId: {
      type: String,
      default: '',
    },
  });
  const emits = defineEmits(['submit']);
  onMounted(async () => {
    await initList();
  });
  async function refreshList(submitData) {
    let res = await getUserViewFormView(props.objectId);
    state.list = [
      {
        name: '全部',
        code: '0',
        id: '0',
        queryType: QUERY_TYPE.QUICK_SEARCH,
        configJson: '',
        formViewType: FormType.SYSTEM,
        isPublic: IS_PUBLIC.PUBLIC,
        objectId: '',
      },
      ...res,
    ];
    if (submitData.id) {
      let activeIndex = -1;
      state.list.some((ele, idx) => {
        if (ele.id === submitData.id && submitData.id == state.activeId) {
          activeIndex = idx;
          return true; // 结束循环
        }
        return false;
      });
      if (activeIndex >= 0) {
        state.name =
          submitData.name +
          (submitData.code == '0'
            ? '（默认）'
            : submitData.isPublic == IS_PUBLIC.PUBLIC
            ? '（公开）'
            : '（个人）');
        state.configJson = submitData.configJson;
        state.combinationFormula = submitData.combinationFormula;
        state.queryType = submitData.queryType;
        state.postData = {
          isPublic: submitData.isPublic,
          id: submitData.id,
          code: submitData.code,
          name: submitData.name,
          formViewType: submitData.formViewType, //表单类型
          configJson: submitData.configJson,
          combinationFormula: submitData.combinationFormula,
          objectId: submitData.objectId, //系统表单formId,自定义表单releaseId的id值
          queryType: submitData.queryType,
        };
        state.list[activeIndex].configJson = state.configJson;
        state.list[activeIndex].combinationFormula = state.combinationFormula;
      }
    }
  }
  async function initList() {
    let res = await getUserViewFormView(props.objectId);
    state.list = [
      {
        name: '全部',
        code: '0',
        id: '0',
        queryType: QUERY_TYPE.QUICK_SEARCH,
        configJson: '',
        formViewType: FormType.SYSTEM,
        isPublic: IS_PUBLIC.PUBLIC,
        objectId: '',
      },
      ...res,
    ];
  }
  function changeActiveId(item) {
    state.activeId = item.id;
    state.name =
      item.name +
      (item.code == '0' ? '（默认）' : item.isPublic == IS_PUBLIC.PUBLIC ? '（公开）' : '（个人）');
    state.configJson = item.configJson;
    state.combinationFormula = item.combinationFormula;
    state.queryType = item.queryType;
    state.postData = {
      isPublic: item.isPublic,
      id: item.id,
      code: item.code,
      name: item.name,
      formViewType: item.formViewType, //表单类型
      configJson: item.configJson,
      combinationFormula: item.combinationFormula,
      objectId: item.objectId, //系统表单formId,自定义表单releaseId的id值
      queryType: item.queryType,
    };
  }
  async function deleteView(id) {
    if (state.activeId == id) {
      // 如果当前选中的是删除的这个，那么替换到默认
      let item = state.list[0];
      changeActiveId(item);
    }
    let res = await deleteFormView(id);
    if (res) {
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      });
      await initList();
    } else {
      notification.error({
        message: t('提示'),
        description: t('删除失败'),
      });
    }
  }
  function search() {
    let combinationFormula = '';
    let Fen_Ge_Fu = '___';
    let jsonStr = 'queryType=' + state.queryType;
    if (state.queryType == QUERY_TYPE.QUICK_SEARCH) {
      let arr = QuickTableRef.value.getDataSource();
      state.configJson = JSON.stringify(arr); //不晓得搜索之后暂时需要保存这个配置
      if (arr && Array.isArray(arr) && arr.length > 0) {
        // 分割规则(分隔符___) 快捷查询  queryType=0 & dan_hang_wen_ben___true(is_date)___我是值
        arr.forEach((element) => {
          let is_date =
            element.schemas.component == 'TimeRangePicker' ||
            element.schemas.component == 'RangePicker' ||
            element.schemas.component == 'time' ||
            element.schemas.component == 'date'
              ? true
              : false;
          if (typeof element.fieldValue != 'undefined') {
            if (typeof element.fieldValue == 'string') {
              if (element.fieldValue != '') {
                jsonStr +=
                  encodeURIComponent('&') +
                  element.fieldName +
                  Fen_Ge_Fu +
                  is_date +
                  Fen_Ge_Fu +
                  element.fieldValue;
              }
            } else if (element.fieldValue == null) {
            } else {
              jsonStr +=
                encodeURIComponent('&') +
                element.fieldName +
                Fen_Ge_Fu +
                is_date +
                Fen_Ge_Fu +
                element.fieldValue;
            }
          }
        });
      }
    } else {
      let arr = AdvancedTableRef.value.getDataSource();
      state.configJson = JSON.stringify(arr); //不晓得搜索之后暂时需要保存这个配置
      if (arr && Array.isArray(arr) && arr.length > 0) {
        // 分割规则(分隔符___) 高级查询  queryType=1 & dan_hang_wen_ben___true(is_date)___0(条件)___0(字段类型)___我是值
        arr.forEach((element) => {
          let is_date =
            element.schemas.component == 'TimeRangePicker' ||
            element.schemas.component == 'RangePicker' ||
            element.schemas.component == 'time' ||
            element.schemas.component == 'date'
              ? true
              : false;
          if (typeof element.fieldValue != 'undefined') {
            if (typeof element.fieldValue == 'string') {
              if ([2, 3, 4, 5, 6, 7].includes(element.fieldType)) {
                element.fieldValue =
                  element.fieldType == 2
                    ? '登录人ID'
                    : element.fieldType == 3
                    ? '登录人组织架构'
                    : element.fieldType == 4
                    ? '登录人所属组织架构及下属组织架构'
                    : element.fieldType == 5
                    ? '登录人账号'
                    : element.fieldType == 6
                    ? '登录人岗位'
                    : element.fieldType == 7
                    ? '登录人角色'
                    : '登录人信息';
                jsonStr +=
                  encodeURIComponent('&') +
                  element.fieldName +
                  Fen_Ge_Fu +
                  is_date +
                  Fen_Ge_Fu +
                  element.conditionType +
                  Fen_Ge_Fu +
                  element.fieldType +
                  Fen_Ge_Fu +
                  element.fieldValue;
              } else if (element.fieldValue != '') {
                jsonStr +=
                  encodeURIComponent('&') +
                  element.fieldName +
                  Fen_Ge_Fu +
                  is_date +
                  Fen_Ge_Fu +
                  element.conditionType +
                  Fen_Ge_Fu +
                  element.fieldType +
                  Fen_Ge_Fu +
                  element.fieldValue;
              }
            } else if (element.fieldValue == null) {
            } else {
              jsonStr +=
                encodeURIComponent('&') +
                element.fieldName +
                Fen_Ge_Fu +
                is_date +
                Fen_Ge_Fu +
                element.conditionType +
                Fen_Ge_Fu +
                element.fieldType +
                Fen_Ge_Fu +
                element.fieldValue;
            }
          }
        });
        // 组合公式  combinationFormula  1 and 2 and 3 or 4
        combinationFormula = AdvancedTableRef.value.getCombinationFormula();
      }
    }
    emits('submit', { advancedQueryConditions: jsonStr, combinationFormula });
    state.modalShow = false;
  }
  async function handleSubmit() {
    let activeIndex = -1;
    state.list.some((ele, idx) => {
      if (ele.id === state.activeId) {
        activeIndex = idx;
        return true; // 结束循环
      }
      return false;
    });
    let postData = state.postData;
    if (postData.queryType == QUERY_TYPE.QUICK_SEARCH) {
      let arr = QuickTableRef.value.getDataSource();
      postData.configJson = JSON.stringify(arr);
      state.configJson = postData.configJson;
      if (activeIndex >= 0) {
        state.list[activeIndex].configJson = state.configJson;
      }
    } else {
      let arr = AdvancedTableRef.value.getDataSource();
      postData.configJson = JSON.stringify(arr);
      state.configJson = postData.configJson;
      let combinationFormula = AdvancedTableRef.value.getCombinationFormula();
      postData.combinationFormula = combinationFormula;
      state.combinationFormula = postData.combinationFormula;
      if (activeIndex >= 0) {
        state.list[activeIndex].configJson = state.configJson;
        state.list[activeIndex].combinationFormula = state.combinationFormula;
      }
    }
    try {
      let val = await updateFormView(postData);
      if (val) {
        notification.success({
          message: t('提示'),
          description: t('保存为视图成功'),
        });
        state.modalShow = false;
      } else {
        notification.error({
          message: t('提示'),
          description: t('保存为视图失败'),
        });
      }
    } catch (error) {
      notification.error({
        message: t('提示'),
        description: t('添加失败'),
      });
      return null;
    }
  }
</script>
<style lang="less" scoped>
  .right-btn {
    margin-right: 6px;
  }

  .btn-box {
    position: relative;
    display: flex;
    align-items: center;
    height: 52px;
    padding-left: 16px;
  }

  .view-box {
    width: 200px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    padding: 0 8px;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 16px;
    height: 32px;
    line-height: 30px;

    .view-title {
      font-size: 14px;
      color: #000;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .column-box {
    display: flex;
    flex-direction: column;
    justify-content: center;

    .border {
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
    }

    .column-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 30px;

      .title {
        font-size: 12px;
        color: #000;
        cursor: pointer;
      }

      .active {
        font-size: 12px;
        color: #5e95ff;
        cursor: pointer;
      }

      .opr {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
      }
    }
  }

  .add-box {
    font-size: 12px;
    color: #5e95ff;
    margin-top: 10px;
  }

  .edit-box {
    font-size: 14px;
    color: #000;
    // color: #5e95ff;
    cursor: pointer;
  }

  .delete-box {
    font-size: 14px;
    // color: #ee8d96;
    cursor: pointer;
  }

  .view-title {
    font-size: 12px;
    color: #000;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .fixed-box {
    position: fixed;
    z-index: 999;
    right: 0;
    background-color: #fff;
    width: 900px;
    top: 0;
    bottom: 0;
    border: 1px solid #d9d9d9;

    .head-box {
      height: 40px;
      display: flex;
      align-items: center;
      padding: 0 10px;
      border-bottom: 1px solid #d9d9d9;

      .head-title {
        font-size: 14px;
        font-weight: 700;
      }
    }

    .action-table {
      width: 100%;
    }

    .action-btn-box {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

    .action-btn {
      position: absolute;
      bottom: 40px;
      right: 10px;
    }
  }
</style>
