<template>
  <div class="row q-mx-md relative-position vt-header-box">
    <search-box v-model="queryMsg.searchKey" @blur="reloadDataHandler"></search-box>
    <q-input class="q-ml-md" outlined dense v-model="queryMsg.formatCreateDateRange" placeholder="创建时间" readonly>
      <q-popup-proxy ref="qDateProxy" transition-show="scale" transition-hide="scale">
        <q-date :options="optionsFn" v-model="queryMsg.createDate" range @range-end="updateCreateRange"></q-date>
      </q-popup-proxy>
    </q-input>
    <q-btn class="q-ml-md q-px-md" :color="queryMsg.customResult.list || queryMsg.whereId != 0 ? 'primary' : 'dark'" label="自定义筛选" dense outline>
      <q-popup-proxy ref="customRef" transition-show="scale" transition-hide="scale" class="q-py-sm">
        <q-list style="width: 250px" dense>
          <q-item clickable v-ripple @click="openWhereBoxHander(1)">
            <q-item-section>
              <q-item-label>自定义筛选</q-item-label>
            </q-item-section>
            <q-item-section side>
              <i class="iconfont icon-arrow-right f12"></i>
            </q-item-section>
          </q-item>
          <q-separator />
          <q-item-label header class="row">
            <div class="col f12">常用筛选</div>
            <div class="text-dark">
              <i class="iconfont icon-setting f12 q-mr-md cursor-pointer" @click="settingWhereList"></i>
              <i class="iconfont icon-plus-circle f12 cursor-pointer" @click="openWhereBoxHander(2)"></i>
            </div>
          </q-item-label>
          <q-item v-for="(x, i) in whereList" :key="i" @click="updateWhereHandler(x.Id)" :active="x.Id == queryMsg.whereId" active-class="text-primary" clickable v-ripple>
            <q-item-section>
              <q-item-label>{{ x.Name }}</q-item-label>
            </q-item-section>
          </q-item>
          <q-separator />
          <q-item clickable v-ripple v-close-popup @click="deleteWhereHandler">
            <q-item-section>
              <q-item-label class="text-primary">清空筛选条件</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-popup-proxy>
    </q-btn>
    <q-btn class="q-ml-md q-px-md" color="dark" label="重置" dense outline @click="deleteWhereHandler(1)"></q-btn>
  </div>
  <q-dialog v-model="showColWhereCard">
    <custom-where :columns="columns" :dataId="dataId" :current="queryMsg.customResult" :code="pageCode" :mode="mode" @change-reload="changeWhereHandler"></custom-where>
  </q-dialog>
  <q-dialog v-model="showWhereList">
    <where-list :code="pageCode" @update-where="editorWhereHandler"></where-list>
  </q-dialog>
</template>

<script>
import searchBox from '../common/searchBox.vue'
import { formatDateTime } from '@/utils/tools'
import { reactive, computed, ref } from 'vue'
import CustomWhere from '../common/customWhere/customWhere.vue'
import whereList from '@/components/common/customWhere/whereList.vue'
import CustomQueryService from '@/api/customQuery'
import { UseDirection } from '@/config/direction'
export default {
  props: {
    /**
     * @description 模式：0为未选择表格内容模式，1为选中了表格内容模式
     */
    model: {
      type: Number,
      default: 0 | 1
    },

    /**
     * @description 列数组
     */
    columns: Array
  },
  components: { searchBox, CustomWhere, whereList },
  setup(props, context) {
    const whereList = ref([])
    const pageCode = ref('clue_custom')
    const showColWhereCard = ref(false)
    const showWhereList = ref(false)
    const customRef = ref(null)
    const mode = ref(1)
    const dataId = ref(0) //声明分类ID，适用于修改分类对应的自定义筛选【mode=3】
    const queryMsg = reactive({
      searchKey: '',
      createDate: {},
      formatCreateDateRange: '',
      whereId: 0,
      customResult: {}
    })
    const selectMsg = reactive({
      CustomerName: '',
      CorpName: '',
      WeChatName: '',
      CustomerMobile: '',
      CreateSTime: '',
      CreateETime: '',
      SelectList: [],
      AddCondition: 1
    })

    const modelType = computed(() => {
      return props.model
    })

    const updateCreateRange = e => {
      if (e.from && e.to) {
        let tempFrom = e.from.year + '-' + e.from.month + '-' + e.from.day
        let toFrom = e.to.year + '-' + e.to.month + '-' + e.to.day
        queryMsg.formatCreateDateRange = `${tempFrom} 至 ${toFrom}`
        selectMsg.CreateSTime = tempFrom
        selectMsg.CreateETime = toFrom
      } else {
        queryMsg.formatCreateDateRange = ''
        selectMsg.CreateSTime = ''
        selectMsg.CreateETime = ''
      }
      qDateProxy.value.hide()
      pushRelaodHandler()
    }

    const nowDate = formatDateTime(new Date(), 'yyyy/MM/dd')
    const optionsFn = date => {
      return date >= '2020/01/01' && date <= nowDate
    }

    const qDateProxy = ref(null)
    const updateWhereHandler = id => {
      queryMsg.whereId = id
      queryMsg.customResult = {}
      selectMsg.SelectList = []
      CustomQueryService.queryCustomById(id).then(r => {
        if (r.data && r.data.Code == 1) {
          selectMsg.SelectList = JSON.parse(r.data.Data.SelectList)
          selectMsg.SelectList = UseDirection.MappingAuto(selectMsg.SelectList)
          selectMsg.AddCondition = r.data.Data.AddCondition
        }
        pushRelaodHandler()
      })
    }

    const deleteWhereHandler = type => {
      queryMsg.customResult = {}
      selectMsg.SelectList = []
      selectMsg.AddCondition = 0
      queryMsg.whereId = 0
      //重置
      if (type == 1) {
        queryMsg.formatCreateDateRange = ''
        queryMsg.createDate = {}
        queryMsg.searchKey = ''
      }
      reloadDataHandler()
    }

    //#region 初始化已保存的自定义信息

    const loadWhereList = () => {
      CustomQueryService.queryMyCustom(pageCode.value).then(r => {
        whereList.value = r.data.Data
      })
    }

    loadWhereList()

    //#endregion

    //#region 处理数据回调

    const reloadDataHandler = () => {
      selectMsg.CustomerName = queryMsg.searchKey
      // selectMsg.CorpName = queryMsg.searchKey
      // selectMsg.WeChatName = queryMsg.searchKey
      // selectMsg.CustomerMobile = queryMsg.searchKey
      if (queryMsg.formatCreateDateRange.indexOf('至') != -1) {
        selectMsg.CreateSTime = queryMsg.formatCreateDateRange.split(' 至 ')[0]
        selectMsg.CreateETime = queryMsg.formatCreateDateRange.split(' 至 ')[1]
      } else {
        selectMsg.CreateSTime = ''
        selectMsg.CreateETime = ''
      }
      pushRelaodHandler()
    }

    const changeWhereHandler = (code, result) => {
      if (code == 'SAVE') {
        loadWhereList()
      } else if (code == 'CUSTOM') {
        queryMsg.customResult = JSON.parse(JSON.stringify(result))
        //selectMsg.SelectList = result.list
        selectMsg.AddCondition = result.condition
        selectMsg.SelectList = UseDirection.MappingAuto(result.list)
        pushRelaodHandler()
      }
      showColWhereCard.value = false
      customRef.value.hide()
    }

    const pushRelaodHandler = () => {
      context.emit('reload-data', selectMsg)
    }

    const openWhereBoxHander = m => {
      mode.value = m
      showColWhereCard.value = true
    }

    const editorWhereHandler = id => {
      showWhereList.value = false
      
      if (id > 0) {
        mode.value = 3 //3 代表编辑
        dataId.value = id
      } else {
        mode.value = 2
      }
      showColWhereCard.value = true
    }

    const settingWhereList=()=>{
       showColWhereCard.value = false
      showWhereList.value = true
    }

    //#endregion
    return { queryMsg, modelType, customRef,settingWhereList, showWhereList, dataId, editorWhereHandler, updateCreateRange, openWhereBoxHander, changeWhereHandler, optionsFn, qDateProxy, mode, whereList, updateWhereHandler, deleteWhereHandler, showColWhereCard, pageCode, reloadDataHandler }
  }
}
</script>

<style>
.vt-header-box .q-field--outlined.q-field--readonly .q-field__control:before {
  border-style: solid !important;
}
</style>
