<template>
  <div :class="$style.searchdiv">
    <div :class="[$style.treewrap, { [$style.collapse]: fold }]">
      <a-card>
        <a-tree
          v-if="!spinning"
          :tree-data="treeData"
          :default-expanded-keys="['-1']"
          :default-selected-keys="['-1']"
          @select="treeSelectd"
        />
        <a-spin :spinning="spinning" :class="$style.spinning" />
      </a-card>
      <a-button type="primary" :class="$style.fold" @click="foldClick">
        <a-icon :type="fold ? 'right' : 'left'" />
      </a-button>
    </div>
    <div :class="$style.rightArea">
      <a-card :class="$style.searchWrap">
        <div>
          <dl :class="$style.selectdl">
            <dt>您已选择：</dt>
            <dd v-show="draftArr.length > 0">
              起草日期：<a-tag
                v-for="(item, i) in draftArr"
                :key="i"
                closable
                @close="closeTag(item, '起草日期')"
              >
                {{ item }}
              </a-tag>
            </dd>
            <dd v-show="flowArr.length > 0">
              流转状态：<a-tag
                v-for="(item, i) in flowArr"
                :key="i"
                closable
                @close="closeTag(item, '流转状态')"
              >
                {{ item }}
              </a-tag>
            </dd>
          </dl>
        </div>
        <a-divider dashed />
        <div>
          <dl :class="$style.searchdl">
            <dt>起草日期：</dt>
            <dd>
              <div v-show="draftDateSingle" :class="$style.single">
                <span
                  v-for="(item, index) in draftDate"
                  :key="index"
                  :class="[index === draftCurrent ? $style.active : '']"
                  @click="typeClick('起草日期', item, index)"
                >
                  {{ item.label }}</span
                >
              </div>
              <a-checkbox-group
                v-show="!draftDateSingle"
                v-model="draftArrCheckedList"
                :options="draftDate"
                @change="draftChange"
              />
            </dd>
            <div :class="$style.isSingle">
              <a-button v-show="draftDateSingle" @click="goisSingle('draftDate')">+ 多选</a-button>
              <a-button
                v-show="!draftDateSingle"
                :class="$style.btnreset"
                @click="goisSingle('draftDate')"
              >
                取消
              </a-button>
              <a-button
                v-show="!draftDateSingle"
                :class="$style.btnreset"
                type="primary"
                @click="draftDateOK"
              >
                确定
              </a-button>
            </div>
          </dl>
          <dl :class="$style.searchdl">
            <dt>流转状态：</dt>
            <dd>
              <div v-show="flowstateSingle" :class="$style.single">
                <span
                  v-for="(item, index) in flowstate"
                  :key="index"
                  :class="[index === flowCurrent ? $style.active : '']"
                  @click="typeClick('流转状态', item, index)"
                >
                  {{ item.label }}</span
                >
              </div>
              <a-checkbox-group
                v-show="!flowstateSingle"
                v-model="flowArrCheckedList"
                :options="flowstate"
                @change="flowChange"
              />
            </dd>

            <div :class="$style.isSingle">
              <a-button v-show="flowstateSingle" @click="goisSingle('flowstate')">+ 多选</a-button>
              <a-button
                v-show="!flowstateSingle"
                :class="$style.btnreset"
                @click="goisSingle('flowstate')"
              >
                取消
              </a-button>
              <a-button
                v-show="!flowstateSingle"
                :class="$style.btnreset"
                type="primary"
                @click="flowstateOK"
              >
                确定
              </a-button>
            </div>
          </dl>
        </div>
        <a-divider dashed />
        <a-form :form="form" layout="inline" :class="$style.precise">
          <a-row>
            <a-form-item ref="name" label="发起人:">
              <sd-user-picker v-model="form.name" :single="false" :read-only="false" />
            </a-form-item>
            <a-form-item ref="title" :class="$style.subject" label="标题:">
              <a-input v-model="form.title" allow-clear />
            </a-form-item>

            <a-form-item label="">
              <a-checkbox v-model="isMyCreate" @change="onChangeMyCreate">
                我起草的
              </a-checkbox>
            </a-form-item>
          </a-row>
          <a-row :class="$style.btnbuttom">
            <a-col :span="24">
              <a-button :class="$style.btnreset" :loading="exportLoading" @click="exportExcel">
                导出
              </a-button>
              <a-button :class="$style.btnreset" @click="handleReset">
                重置
              </a-button>
              <a-button
                :class="$style.btnreset"
                type="primary"
                html-type="submit"
                @click="onSubmit"
              >
                查询
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card :class="$style.tablecard">
        <sd-data-table
          ref="dataTable"
          data-url="api/framework/v1/workflow-search-center/workflow-List"
          :columns="columns"
          :row-key="(record, index) => index"
          :process-req="processReq"
          :pagination="expand ? { pageSize: 5 } : { pageSize: 10 }"
          @rowClick="rowClick"
        >
        </sd-data-table>
      </a-card>
    </div>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import moment from 'moment'
import storeMixin from '@/common/store-mixin'
import TableColumnTypes from '@/common/services/table-column-types'
import { Message } from 'ant-design-vue'
import todoListService from '@/todo/todo-list-service'
import components from './_import-components/sd-process-search-import'

const formatTreeData = (arr) => {
  arr.forEach((item) => {
    item.title = item.title || item.text
    item.isLeaf = item.leaf
    item.key = item.id
    if (item.children) formatTreeData(item.children)
  })
}
const columns = [
  {
    title: '业务类型',
    dataIndex: 'businessTypeName',
  },
  {
    title: '标题',
    dataIndex: 'title',
    sdClickable: true,
  },
  {
    title: '发起人',
    dataIndex: 'starterUserName',
  },
  {
    title: '发起部门',
    dataIndex: 'starterDeptName',
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sorter: true,
    sdRender: TableColumnTypes.dateTime,
    defaultSortOrder: 'desc',
  },
  {
    title: '处理状态',
    dataIndex: 'flowStateName',
  },
  {
    title: '当前处理人',
    dataIndex: 'currentHandler',
  },

  {
    title: '办结时间',
    dataIndex: 'finishTime',
    sdRender: TableColumnTypes.dateTime,
  },
]
export default {
  name: 'SdProcessSearch',
  metaInfo: {
    title: '流程查询',
  },
  components,
  mixins: [storeMixin],
  data() {
    return {
      draftCurrent: 1,
      flowCurrent: 2,
      searchCurrent: 0,
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      form: {
        name: [],
        dept: '',
        createdate: undefined,
        title: '',
      },
      columns,
      expand: true, // 默认搜索条件为展开状态
      flowstateSingle: true, // 流转状态单选
      draftDateSingle: true, // 起草日期
      isMyCreate: false, // 我起草的
      businessType: [], // 业务类型
      flowstate: [
        // 流转状态
        { label: '不限', value: 'all' },
        { label: '起草中', value: '起草中' },
        { label: '待处理', value: '待处理' },
        { label: '已处理', value: '已处理' },
        { label: '已办结', value: '已办结' },
        { label: '已作废', value: '已作废' },
      ],

      businessArr: [], // 业务类型数组
      draftArr: [],
      draftArrCheckedList: [],
      flowArr: [],
      flowArrCheckedList: [],

      params: {
        businessTypeList: [],
        draftMonthList: [],
        draftYearList: [],
        flowStateList: [],
        startAccountList: [],
        title: '',
      }, // 查询条件
      exportLoading: false, // 导出按钮loading状态
      fold: true,
      treeData: [
        {
          differentDisplay: false,
          children: [],
          expandable: true,
          leaf: false,
          props: {},
          id: '-1',
          text: '业务类型',
        },
      ],
      spinning: true,
    }
  },
  computed: {
    draftDate() {
      // 年份
      const years = [{ label: '不限', value: 'all' }]
      // 先写死10年进行调试
      for (let index = 0; index < 10; index++) {
        const year = moment()
          .add(-index, 'y')
          .format('YYYY')
        years.push({ label: Number(year), value: Number(year) })
      }
      return years
    },
  },
  created() {
    this.getTreeData()
    this.typeClick('起草日期', this.draftDate[this.draftCurrent], this.draftCurrent)
    this.typeClick('流转状态', this.flowstate[this.flowCurrent], this.flowCurrent)
    this.onSubmit()
    // 查询条件变化时刷新数据
    this.$watch('params', () => {
      this.$refs.dataTable.refresh(true)
    })
    this.$watch('draftArr', (val) => {
      if (val.length < 1) {
        this.draftCurrent = 0
      }
      this.onSubmit()
    })
    this.$watch('flowArr', (val) => {
      if (val.length < 1) {
        this.flowCurrent = 0
      }
      this.onSubmit()
    })
  },
  methods: {
    // 我起草的
    onChangeMyCreate(e) {
      if (e.target.checked) {
        this.isMyCreate = true
        this.form.name = []
      } else this.isMyCreate = false
    },
    // 展开或收起
    changeexpand() {
      this.expand = !this.expand
    },
    // 点击查看详情
    rowClick(record) {
      if (['已处理', '已办结'].includes(record.flowStateName)) {
        record.wfBusiId = record.id
      }
      // 查出来的自己不一定能操作，跳转到一个不可编辑页面
      todoListService.openTaskItem(record).then((refreshFlag) => {
        if (refreshFlag) this.$refs.dataTable.refresh()
      })
    },
    onSubmit() {
      // 流转状态
      const flowStateList = []
      this.flowArr.forEach((item) => {
        switch (item) {
          case '起草中':
            flowStateList.push('draft')
            break
          case '待处理':
            flowStateList.push('inprocess')
            break
          case '已处理':
            flowStateList.push('processed')
            break
          case '已办结':
            flowStateList.push('completed')
            break
          case '已作废':
            flowStateList.push('invalid')
            break

          default:
            break
        }
      })
      // 业务类型
      const businessTypeList = this.businessArr

      // 查询年份
      let draftYearList = []
      if (this.draftArr && this.draftArr[0]) draftYearList = this.draftArr
      // 月份
      const draftMonthList = []
      // 发起人
      let startAccountList = []
      this.form.name.forEach((item) => {
        startAccountList.push(item.code)
      })
      // 我起草的
      if (this.isMyCreate) {
        startAccountList = []
        startAccountList.push(this.userInfo.account)
      }
      // 标题
      let title = ''
      title = this.form.title
      // 查询
      this.params = {
        businessTypeList,
        draftMonthList,
        draftYearList,
        flowStateList,
        startAccountList,
        title,
      }
    },
    // 查询比较特殊不能直接用expressions，在这里新增查询条件
    processReq(req) {
      req.data.businessTypeList = this.params.businessTypeList
      req.data.draftMonthList = this.params.draftMonthList
      req.data.draftYearList = this.params.draftYearList
      req.data.flowStateList = this.params.flowStateList
      req.data.startAccountList = this.params.startAccountList
      req.data.title = this.params.title
      return req
    },
    handleReset() {
      this.isMyCreate = false
      this.draftArr = []
      this.flowArr = []
      this.form.title = ''
      this.form.name = []
      this.typeClick('起草日期', this.draftDate[1], 1)
      this.typeClick('流转状态', this.flowstate[2], 2)
    },
    // 导出表格数据
    exportExcel() {
      this.exportLoading = true
      this.$refs.dataTable.exportExcel().then(() => {
        this.exportLoading = false
      })
    },
    closeTag(rmtag, type) {
      if (type === '起草日期') {
        const tags = this.draftArr.filter((tag) => tag !== rmtag)
        this.draftArr = tags
        if (this.draftArr.length === 0) this.draftDateSingle = true
      } else if (type === '流转状态') {
        const tags = this.flowArr.filter((tag) => tag !== rmtag)
        this.flowArr = tags
        if (this.flowArr.length === 0) this.flowstateSingle = true
      }
    },
    // 去单选businessSingle
    goisSingle(type) {
      switch (type) {
        case 'draftDate':
          this.draftDateSingle = !this.draftDateSingle
          if (this.draftDateSingle) {
            this.draftArr = []
            this.draftArrCheckedList = []
          }
          break
        case 'flowstate':
          this.flowstateSingle = !this.flowstateSingle
          if (this.flowstateSingle) {
            this.flowArr = []
            this.flowArrCheckedList = []
          }
          break
        default:
      }
    },
    // 点击分类选择
    typeClick(type, item, index) {
      if (type === '起草日期') {
        this.draftCurrent = index
        if (item.value === 'all') {
          this.draftArr = []
          return
        }
        if (this.draftArr.indexOf(item.label) === -1) {
          this.draftArr = []
          this.draftArr.push(item.label)
          this.draftArrCheckedList = []
          this.draftArrCheckedList.push(item.label)
        }
      } else if (type === '流转状态') {
        this.flowCurrent = index
        if (item.value === 'all') {
          this.flowArr = []
          this.flowArrCheckedList = []
          return
        }
        if (this.flowArr.indexOf(item.label) === -1) {
          this.flowArr = []
          this.flowArr.push(item.label)
          this.flowArrCheckedList = []
          this.flowArrCheckedList.push(item.label)
        }
      }
    },

    draftChange(checkedList) {
      if (checkedList.indexOf('all') !== -1) {
        this.draftArr = []
        this.goisSingle('draftDate')
      }
    },

    draftDateOK() {
      if (this.draftArrCheckedList.length > 0) {
        this.draftArr = []
        this.draftArrCheckedList.forEach((element) => {
          this.draftArr.push(element)
        })
      } else {
        Message.warning('请选择起草日期')
      }
    },

    flowChange(checkedList) {
      if (checkedList.indexOf('all') !== -1) {
        this.flowArr = []
        this.goisSingle('flowstate')
      }
    },

    flowstateOK() {
      if (this.flowArrCheckedList.length > 0) {
        this.flowArr = []
        this.flowArrCheckedList.forEach((element) => {
          this.flowArr.push(element)
        })
      } else {
        Message.warning('请选择流转状态')
      }
    },
    foldClick() {
      this.fold = !this.fold
      this.$refs.dataTable.handleResize()
    },
    getTreeData() {
      axios.get('api/framework/v1/newflow/auth-businesstypes').then((res) => {
        this.treeData[0].children = res.data
        formatTreeData(this.treeData)
        this.spinning = false
      })
    },
    // 当工作树选择了业务类型时更新筛选条件
    treeSelectd(ywlxInfo) {
      const categoryId = ywlxInfo[0]
      if (this.businessArr[0] === categoryId) {
        return
      }
      if (categoryId === '-1' || !categoryId) {
        this.businessArr = []
      } else {
        this.businessArr = [categoryId]
      }
      this.onSubmit()
      // 点击树时将tableDataReady改一下
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.selectdl {
  overflow: hidden;
  dt {
    float: left;
  }
  dd {
    float: left;
    margin-bottom: 0;
  }
}

.searchdl {
  overflow: hidden;
  .active {
    color: $primary-color;
  }
  .is-single {
    float: right;
  }
  dt {
    float: left;
  }
  dd {
    float: left;
    width: 80%;
    .single {
      overflow: hidden;
      > span {
        display: inline-block;
        float: left;
        padding: 0 10px;
        cursor: pointer;
      }
    }
  }
}
.btnbuttom {
  float: right;
}
.btnreset {
  margin: 5px;
}

.searchdiv {
  display: flex;
  flex: auto;
  height: 100%;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
}
.tablecard {
  min-height: 50%;
}
.ywlxlefttd {
  min-width: 90px;
  vertical-align: middle;
}
.ywlxrighttd {
  width: 100%;
}
.precise {
  display: flex;
  justify-content: space-between;
  :global(.ant-form-item-control-wrapper) {
    width: 200px;
  }
}
.subject {
  :global(.ant-form-item-control-wrapper) {
    min-width: 350px;
  }
}
.right-area {
  flex: 1;
  width: calc(100% - 20%);
  height: 100%;
  overflow-y: auto;
}
.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;
    }
  }
}
.spinning {
  margin-left: 45%;
}
</style>
