<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <div :class="[$style.treewrap, { [$style.collapse]: fold }]">
        <a-card>
          <a-tree
            show-icon
            :tree-data="treeData"
            :replace-fields="replacefields"
            :selected-keys="selectedkey"
            :load-data="onLoadData"
            :expanded-keys.sync="expandedKeys"
            @select="onSelect"
          >
            <template slot="title" slot-scope="{ text, props }">
              <span :title="text">{{ text }}</span
              ><span v-if="props.count > 0">（{{ props.count }}）</span>
            </template>
          </a-tree>
        </a-card>
        <a-button type="primary" :class="$style.fold" @click="foldClick">
          <a-icon :type="fold ? 'right' : 'left'" />
        </a-button>
      </div>
      <div :class="$style.rightcard">
        <SdAdvanceSearch
          v-show="advSearchBtnActived"
          :class="$style.formCard"
          @search="submit"
          @reset="reset"
          @close="
            () => {
              reset()
              advSearchBtnActived = false
            }
          "
        >
          <a-form :class="$style.form" v-bind="formItemLayout">
            <a-row>
              <a-col :span="8">
                <a-form-item label="发起人">
                  <sd-user-picker v-model="form.listCreator" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="发起部门">
                  <sd-group-picker v-model="form.listCreateDeptId" />
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item label="当前处理人">
                  <sd-user-picker v-model="form.accounts" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item label="标题">
                  <a-input v-model="form.title"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16"
                ><a-form-item label="创建时间" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
                  <a-radio-group
                    v-model="form.period"
                    default-value="all"
                    button-style="solid"
                    @change="dateChange"
                  >
                    <a-radio-button value="oneweek">
                      一周内
                    </a-radio-button>
                    <a-radio-button value="onemonth">
                      一个月内
                    </a-radio-button>
                    <a-radio-button value="custom">
                      自定义
                    </a-radio-button>
                  </a-radio-group>
                  <a-range-picker
                    v-show="form.period === 'custom'"
                    v-model="form.createTime"
                    :class="$style.datepicker"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </SdAdvanceSearch>
        <a-card :class="$style.tableCard">
          <sd-data-table
            v-if="showTable"
            ref="datatable"
            data-url="api/framework/v1/flows/instList"
            :columns="progressFlowColums"
            :actions="progressFlowActions"
            :row-key="'instId'"
            :filter-expressions="expressions"
            :process-req="processReq"
            :search-fields="showfuzzySearch ? ['title'] : []"
            :class="$style.fuzzyAdvSearch"
            show-selection
            @rowClick="rowClick"
          >
            <!-- 高级查询 -->
            <template slot="headerPrefix">
              <SdAvanceSearchBtn
                :actived="advSearchBtnActived"
                :class="$style.advsearchbtn"
                @click="switchSearch"
              />
            </template>
          </sd-data-table>
          <a-spin v-else :class="$style.spinning" />
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import axios from '@/common/services/axios-instance'
import TableActionTypes from '@/common/services/table-action-types'
import SdAvanceSearchBtn from '@/application-manage/sd-advance-search-btn.vue'
import SdAdvanceSearch from '@/application-manage/sd-advance-search.vue'
import components from './_import-components/sd-my-flowlist-import'
import sdflowForm from './sd-flow-form-mixins'
const handleTreeData = (arr) => {
  arr.forEach((item) => {
    if (item.children) handleTreeData(item.children)
    item.isLeaf = item.leaf
  })
}
export default {
  name: 'SdMyFlowlist',
  metaInfo: {
    title: '流程管理',
  },
  components: {
    ...components,
    SdAdvanceSearch,
    SdAvanceSearchBtn,
  },
  mixins: [sdflowForm],
  data() {
    return {
      fold: true,
      treeData: [],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      replacefields: {
        title: 'text',
        key: 'id',
      },
      selectedkey: [],
      expandedKeys: [],
      progressFlowActions: [
        {
          label: '删除',
          id: 'archives',
          permission: null,
          type: TableActionTypes.batch,
          callback: (keys) => {
            this.remove(keys)
          },
        },
      ],
      applicationId: '',
      businessTypeIds: '',
      form: {
        listCreator: '',
        listCreateDeptId: '',
        accounts: '',
        title: '',
        period: '',
        createTime: null,
      },
      searchExpressions: [],
      showfuzzySearch: true,
      advSearchBtnActived: false,
    }
  },
  computed: {
    showTable() {
      return !this.applicationId || this.businessTypeIds
    },
    expressions() {
      let expressions = this.businessTypeIds
        ? [
            {
              dataType: 'str',
              name: 'appId',
              op: 'in',
              stringValue: this.businessTypeIds,
            },
          ]
        : []
      if (this.searchExpressions.length) {
        expressions = [...this.searchExpressions, ...expressions]
      }
      return expressions
    },
  },
  created() {
    this.applicationId = this.$route.query.appId
    this.getTreeData()
  },
  methods: {
    processReq(req) {
      if (this.form.accounts) {
        req.data.accounts = this.form.accounts.map((item) => item.code)
      }
      return req
    },
    getTreeData() {
      const params = {
        appId: this.applicationId,
      }
      axios({
        url: `api/framework/v1/we-app-flow-center/${
          this.applicationId ? 'app-businesstype-tree' : 'businesstype-tree'
        }`,
        method: 'get',
        params,
      }).then((res) => {
        this.treeData = res.data
        handleTreeData(this.treeData)
        this.expandedKeys = [res.data[0]?.id]
        this.selectedkey = [res.data[0]?.id]
        this.businessTypeIds = res.data[0]?.props?.businessTypeIds
      })
    },
    onLoadData(treeNode) {
      if (treeNode.dataRef.children) {
        return Promise.resolve()
      }
      const params = {}
      if (treeNode.dataRef.props?.appId) {
        params.appId = treeNode.dataRef.props.appId
      }
      if (treeNode.dataRef.props?.categoryId) {
        params.categoryId = treeNode.dataRef.props.categoryId
      }
      return axios({
        url: `api/framework/v1/we-app-flow-center/${
          this.applicationId ? 'app-businesstype-tree' : 'businesstype-tree'
        }`,
        method: 'get',
        params,
      }).then((res) => {
        treeNode.dataRef.children = res.data.map((r) => {
          r.isLeaf = r.leaf
          return r
        })
        this.treeData = [...this.treeData]
      })
    },
    onSelect(selectedKeys, info) {
      this.selectedkey = selectedKeys
      this.selectNode = info.node.dataRef
      this.businessTypeIds = info.node.dataRef.props?.businessTypeIds
    },
    dateChange() {
      switch (this.form.period) {
        case 'oneweek': {
          this.form.createTime = [moment().subtract(7, 'days'), moment()]
          break
        }
        case 'onemonth': {
          this.form.createTime = [moment().subtract(1, 'months'), moment()]
          break
        }
      }
    },
    foldClick() {
      this.fold = !this.fold
      this.$refs.datatable.handleResize()
    },
    reset() {
      this.form = {
        listCreator: '',
        listCreateDeptId: '',
        accounts: '',
        title: '',
        period: '',
        createTime: null,
      }
      this.searchExpressions = []
    },
    submit() {
      this.searchExpressions = []
      const { listCreator, listCreateDeptId, title, period, createTime } = this.form
      if (listCreator.length) {
        this.searchExpressions.push({
          name: 'listCreator',
          op: 'eq',
          stringValue: listCreator.map((item) => item.code).toString(),
          dataType: 'str',
        })
      }
      if (listCreateDeptId.length) {
        this.searchExpressions.push({
          name: 'listCreateDeptId',
          op: 'eq',
          stringValue: listCreateDeptId.map((item) => item.code).toString(),
          dataType: 'str',
        })
      }
      if (title) {
        this.searchExpressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: '%' + title + '%',
        })
      }
      if (createTime && createTime.length > 0) {
        let startTime = moment(moment(createTime[0])).valueOf()
        let endTime = moment(moment(createTime[1])).valueOf()
        if (period === 'custom') {
          startTime = moment(moment(createTime[0]))
            .startOf('day')
            .valueOf()
          endTime = moment(moment(createTime[1]))
            .endOf('day')
            .valueOf()
        }
        this.searchExpressions.push(
          {
            dataType: 'dateTime',
            name: 'listStartDate',
            op: 'ge',
            dateTimeValue: startTime,
          },
          {
            dataType: 'dateTime',
            name: 'listStartDate',
            op: 'lt',
            dateTimeValue: endTime,
          }
        )
      }
    },
    // 切换查询（高级查询、模糊查询）
    switchSearch() {
      if (this.advSearchBtnActived) {
        // 显示了高级查询，则重置
        this.reset()
      } else {
        // 未显示高级查询，则置空模糊查询
        this.showfuzzySearch = false
        this.$refs.datatable.onSearchChange('')
        this.$nextTick(() => {
          this.showfuzzySearch = true
        })
      }
      this.advSearchBtnActived = !this.advSearchBtnActived
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/application-manage/advance-search.scss';
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
      overflow-y: auto;
      .form-card {
        margin-bottom: 10px;
      }
      .table-card {
        flex: 1;
      }
    }
  }
}
.spinning {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.treewrap {
  position: relative;
  display: flex;
  width: 20%;
  min-height: 100%;
  margin-right: $padding-lg;
  transition: width 0.2s;
  &.collapse {
    :global(.ant-card) {
      display: none;
    }
  }
  :global(.ant-card) {
    width: 100%;
    height: 100%;
    overflow: auto;
    :global(.ant-card-body) {
      background: $white;
    }
  }
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 15px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.collapse {
  width: 0;
  :global(.ant-card-body) {
    background: transparent;
    :global(.ant-empty) {
      display: none;
    }
  }
}
.datepicker {
  margin-left: 40px;
}
</style>
