<template>
  <div :class="[$style.dataSelector, 'ant-layout']">
    <sdSearchForm
      v-if="onlListColumnDefs.length"
      v-show="showAdvSearch"
      ref="searchForm"
      :onl-list-column-defs="onlListColumnDefs"
      :class="$style.search"
      @search="(value) => (customFilterExpressions = value)"
      @close="() => (advSearchBtnActived = false)"
    />
    <a-card :class="[$style.card, 'sd-has-table']">
      <a-tabs
        v-model="activeTab"
        :class="{ ['sd-has-table']: true, [$style.hiddenTab]: tabs.length === 1 }"
      >
        <a-tab-pane v-for="{ key, tab, filterExpressions } in computedTabs" :key="key" :tab="tab">
          <sd-data-table
            :ref="`dataTable_${key}`"
            data-url="api/framework/v1/page/businessList"
            :process-req="processReq"
            :process-res="processRes"
            :columns="columns"
            :selected-datas="selectedDatas"
            :filter-expressions="filterExpressions"
            :search-fields="searchFields"
            :class="{ [$style.fuzzyAdvSearch]: fuzzyAndAdvSearch }"
            @rowClick="showDetail"
          >
            <template slot="id" slot-scope="text">
              <component
                :is="single ? Radio : Checkbox"
                :checked="!!selectedKeys.find((key) => text === key)"
                @click="(e) => onCheckboxClick(text)"
              />
            </template>
            <!-- 既有高级查询，又有模糊查询，显示高级查询图标 -->
            <template v-if="fuzzyAndAdvSearch" slot="headerPrefix">
              <SdAvanceSearchBtn
                :actived="advSearchBtnActived"
                :class="$style.advsearchbtn"
                @click="switchSearch"
              />
            </template>
          </sd-data-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <!-- 详情页 -->
    <a-modal
      v-model="detailModal"
      destroy-on-close
      :title="detailFormData.pageTitle"
      v-bind="{ width: 800 }"
      :mask-closable="false"
    >
      <component
        :is="sdform"
        :init-values="sdGet(detailFormData, '.pageFormData?.pageFieldInfos')"
        read-only
      >
        <SdFormByBuilder :form-data="detailFormData.pageFormData" />
      </component>
      <template slot="footer">
        <a-button @click="detailModal = false">退出</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { Radio, Checkbox } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import formula2exps from '@/application-manage/formula-2-exps'
import sdSearchForm from '@/application-manage/sd-search-form'
import TableColumnTypes from '@/common/services/table-column-types'
import SdAvanceSearchBtn from '@/application-manage/sd-advance-search-btn.vue'
import todoListService from '@/todo/todo-list-service'
import asyncComponent from '@/common/services/async-component'
import { filterFormula2Exps } from '@/application-manage/sd-list-mixin.vue'
import components from './_import-components/sd-picker-link-data-import'
import pickerSourceMixin from './picker-source-mixin'
export default {
  name: 'SdPickerLinkData',
  metaInfo: {
    title: '',
  },
  components: {
    sdSearchForm,
    ...components,
    SdAvanceSearchBtn,
    SdFormByBuilder: () => import('@/common/components/sd-form-by-builder.vue'),
  },
  mixins: [pickerSourceMixin],
  props: {
    formId: {
      type: String,
      default: undefined,
    },
    formListId: {
      type: String,
      default: undefined,
    },
    isFlow: {
      type: Boolean,
      default: false,
    },
    customValues: {
      type: [String, Object],
      default: () => ({}),
    },
  },
  data() {
    return {
      tabs: [],
      activeTab: undefined,
      showfuzzySearch: true,
      advSearchBtnActived: false,
      onlListColumnDefs: [],
      detailFormData: {},
      detailModal: false,
      customFilterExpressions: [],
      selectedDatas: [],
      selectedRowKey: '',
      Radio,
      Checkbox,
      sdform: asyncComponent(() =>
        import(/* webpackChunkName: "sd-form" */ '@/common/components/sd-form.vue')
      ),
    }
  },
  computed: {
    searchFields() {
      if (this.isFlow) {
        // 流程表单，直接以标题为模糊搜索条件
        if (this.showfuzzySearch) {
          return ['title']
        }
      } else {
        // 非流程表单，获取第一个显示列为模糊搜索条件
        if (this.showfuzzySearch) {
          const columns = this.columns
          if (columns[1]) {
            return [columns[1].dataIndex]
          }
        }
      }
      return []
    },
    fuzzyAndAdvSearch() {
      // 既有高级查询，又有模糊查询
      return this.onlListColumnDefs.some((item) => item.search) && this.searchFields.length > 0
    },
    showAdvSearch() {
      if (this.fuzzyAndAdvSearch) {
        return this.advSearchBtnActived
      }
      return this.onlListColumnDefs.length
    },
    columns() {
      return [
        {
          title: '',
          dataIndex: 'id',
          scopedSlots: { customRender: 'id' },
          width: '60px',
          show: true,
        },
      ]
        .concat(
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.onlListColumnDefs
            .sort((a, b) => a.showSeq - b.showSeq)
            .map((item, index) => {
              let sdRender
              if (item.fieldType === 'date') {
                if (item.fieldAttr.showDate === 'true' && item.fieldAttr.showTime === 'true') {
                  sdRender = TableColumnTypes.dateTime
                } else if (item.fieldAttr.showDate === 'true') {
                  sdRender = TableColumnTypes.date
                } else {
                  sdRender = TableColumnTypes.time
                }
              }
              return {
                title: item.fieldName,
                dataIndex: item.fieldId,
                sorter: item.sort,
                sdClickable: item.attrFD?.clickable ?? true,
                sdRender,
                show: item.show,
                ...item.attrFD,
                sdCandidate: item.show === 2,
              }
            })
        )
        .filter((item) => item.show)
    },
    computedTabs() {
      return this.tabs.map((tab) => {
        return {
          ...tab,
          filterExpressions: [...tab.filterExpressions, ...this.customFilterExpressions],
        }
      })
    },
  },
  created() {
    return axios
      .get('api/framework/v1/we-app-module/get-module-id?formId=' + this.formId)
      .then((res) => {
        return axios
          .get(
            `api/framework/v1/we-app-form-list/show?appModuleId=${res.data.moduleId}${
              this.formListId ? '&formListId=' + this.formListId : ''
            }`
          )
          .then((res) => {
            this.onlListColumnDefs = res.data.onlListColumnDefs
            this.tabs = res.data.attr?.tabs?.map((tab, index) => {
              return {
                key: index + '',
                tab: tab.label,
                filterExpressions: formula2exps(tab.value),
              }
            })
            if (!this.tabs?.length) {
              if (this.isFlow) {
                this.tabs = [
                  {
                    key: 'done',
                    tab: '已办结',
                    filterExpressions: [
                      {
                        dataType: 'int',
                        name: 'FLOW_STATUS',
                        op: 'eq',
                        intValue: 5,
                      },
                    ],
                  },
                  {
                    key: 'doing',
                    tab: '办理中',
                    filterExpressions: [
                      {
                        dataType: 'int',
                        name: 'FLOW_STATUS',
                        op: 'lt',
                        intValue: 5,
                      },
                    ],
                  },
                ]
              } else {
                this.tabs = [
                  {
                    key: 'done',
                    tab: '全部',
                    filterExpressions: [],
                  },
                ]
              }
            }
            // 列表过滤公式转换为查询条件
            const filterExps = filterFormula2Exps(
              res.data.attr?.filterFormulaObject,
              this.customValues
            )
            if (filterExps) {
              this.tabs.forEach((item) => {
                item.filterExpressions = item.filterExpressions.concat(filterExps)
              })
            }
            this.activeTab = this.tabs[0].key
          })
      })
  },
  methods: {
    showDetail(record) {
      // 无流程表单
      if (!this.isFlow) {
        axios
          .get(`api/framework/v1/page/wp/onl:${this.formId}`, {
            params: { id: record.id },
          })
          .then((res) => {
            this.detailFormData = res.data
            this.detailModal = true
          })
      } else {
        // 流程表单
        todoListService.openTaskItem(record)
      }
    },
    // 切换查询（高级查询、模糊查询）
    switchSearch() {
      if (this.advSearchBtnActived) {
        // 显示了高级查询，则重置
        this.$refs.searchForm.reset()
      } else {
        // 未显示高级查询，则置空模糊查询
        this.showfuzzySearch = false
        this.tabs.forEach((tab) => {
          this.$refs[`dataTable_${tab.key}`]?.[0]?.onSearchChange('')
        })
        this.$nextTick(() => {
          this.showfuzzySearch = true
        })
      }
      this.advSearchBtnActived = !this.advSearchBtnActived
    },
    onCheckboxClick(keyClick) {
      const checked = !this.selectedKeys.find((key) => keyClick === key)
      this.itemSelect(keyClick, checked)
    },
    processReq(req) {
      req.data.formId = 'onlhead:' + this.formId
      return req
    },
    processRes(res) {
      this.updateDataSource([
        ...res.data.map((i) => ({ ...i, name: i.name || 'placeholder' })),
        ...this.dataSource,
      ])
      return res
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/application-manage/advance-search.scss';
.data-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  .search {
    margin-bottom: 10px;
  }
  > div:last-child {
    flex: 1;
    min-height: auto;
  }
  :global(.ant-table-title) {
    display: none;
  }
  form + div {
    float: right;
  }
  .card {
    :global(.ant-card-body) {
      padding-right: 0;
      padding-bottom: 0;
      padding-left: 0;
    }
  }
}
.hidden-tab {
  :global(.ant-tabs-bar) {
    visibility: hidden;
  }
}
</style>
