<template>
  <div>
    <p class=" text-2xl font-bold mb-5">聊天管理</p>
     <!-- timepicker -->
      <span class=" font-semibold">发布时间：</span>
      <timerange class=" mr-3"
                 @getNewTime="getNewTime"
                 :startTime="searchPageReqParams.startTime"
                :endTime="searchPageReqParams.endTime"/>
      <!-- 操作 -->
      <a-button type="primary" style=" margin-right:10px;" @click="fetchList">查询</a-button>
      <a-button type="primary" style=" margin-right:10px;" @click="reset">重置</a-button>
      <a-button type="primary" @click="show=true">创建</a-button>
      <!-- 发布弹窗 -->
      <a-modal v-model="show" title="设置常用问题、自动回复" :centered="true" footer="" style="text:center">
        <a-form-model :model="form" ref="ruleForm">
          <a-form-model-item style="justify-content: center;	padding: 4rem;">
            <span v-for="(item,index) of forms" :key="index"  classs=""> 
              <!-- <span v-if="index%2!==0" > -->
                <a-input v-model="item.answer" :placeholder="'设置自动回复'+ index +'（50字以内）'" style="width: 18rem;margin-right:10px;"/>
                <span @click="addInput()">
                  <a-icon type="plus" style=" margin-right:10px;"  />
                </span>
                <span @click="minInput(index)" v-if="index!=0">
                  <a-icon type="minus"/>
                </span>
                <a-input  v-model="item.question" :placeholder="'设置对应常用问题'+ index +'（50字以内）'"  style="width: 18rem;"/>             
            </span>
            <!-- <a-tabs default-active-key="1">
               
               <a-tab-pane key="1" tab="自动回复" >
                <a-input v-for="index of autoSize" :placeholder="'设置自动回复'+index+'（50字以内）'" :key="index"/>
                <div v-if="index%2"></div>
              </a-tab-pane>
              <a-tab-pane key="2" tab="常用问题">
                <a-input v-for="index of commonSize" :placeholder="'常用问题'+index+'（20字以内）'" :key="index"/>
              </a-tab-pane>
            </a-tabs> -->
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 7 }">
            <a-button type="primary" @click="onSubmit">确认</a-button>
            <a-button style="margin-left: 10px;" @click="resetForm">重置</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <!-- 资讯列表 -->
      <a-table :loading="loading" :columns="columns"  :pagination="false" :data-source="list" :rowKey="record=>record.question" style=" text-align: center; margin-top:40px;" bordered>
        <template #created_at='text'>
          {{text | formatDate}}
        </template>
        <template #faq_status='text'>
          {{Status(text)}}
        </template>
        <!-- 新闻内容 -->
        <span slot="content" slot-scope="text,record">
          <a @click="toDetail(record)">查看</a>
        </span>
        <!-- 操作 -->
        <span slot="action" slot-scope="text,record">
          <span  v-if="record.faq_status===1">
            <a @click="add(record)"> 上架</a>
            <a-divider type="vertical" />
            <a @click="onDelete(record)" >删除</a>
          </span>
          <span v-else-if="record.faq_status === 2">
            <a @click="remove(record)">下架</a>
            <a-divider type="vertical" />
            <a style="color: rgba(249, 250, 251, var(--tw-text-opacity));">删除</a>
          </span>
          <!-- <span v-if="record.state=='已发布' && record.type=='自动回复'">
            <a-divider type="vertical" />
            <a @click="setDefault(record.key)">设为默认</a>
          </span> -->
        </span>
    </a-table>
    <!-- 操作Modal -->
    <a-modal
      :title="title"
      v-model="visible"
      :centered="true"
      :closable="false"
      @ok="handleOk"
      @cancle="visible = false"
    >
      <p class=" text-center">{{text}}</p>
    </a-modal>
    <a-pagination
      class="text-right mt-4"
      :current="Current"
      :total="total"
      :pageSize="PAGE_SIZE"
      @change="handlePaginationChange"
    ></a-pagination>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
// import { chatList } from '@/mock/index'
import { FAQItem } from '@/service/FAQService/type'
import { columns } from '@/const/columns/chatColumns'
import { FormModel } from 'ant-design-vue'
import { modal } from './const'
import timerange from '@/components/TimePicker/index.vue'
import { Tabs } from 'ant-design-vue'
Vue.use(Tabs)
import FAQService from '@/service/FAQService/index'
import { eAQRStatus } from '@/types/chat'
import { PAGE_SIZE } from '@/const/config/page'
import { number } from 'echarts'

interface AQRaq { 
    answer: string; 
    question: string; 
} 
export default Vue.extend({
  components:{ timerange },
  computed:{
    columns(){
      return columns
    },
    // autoSize(){
    //   let count:number = 2
    //   const max:number = 4
    //   chatList.forEach(m=>{
    //     if(m.type == '自动回复') count++
    //   })
    //   return max-count
    // },
    // commonSize(){
    //   let count:number = 0
    //   let max:number = 2
    //   chatList.forEach(m=>{
    //     if(m.type == '常见问题') count++
    //   })
    //   return max-count
    // },
    list():FAQItem[]{
      return this.chatList
    },
    Current():number{
      return this.searchPageReqParams.offset / this.searchPageReqParams.limit + 1
    }
  },
  created(){
    this.addInput()
  },
  mounted(){
    this.fetchList()
  },
  data(){
    return{
      searchPageReqParams: {
        startTime: undefined as undefined | number,
        endTime: undefined as undefined | number,
        limit:PAGE_SIZE,
        faq_status: 0,
        offset: 0,
      },
      show:false,
      count:1,
      form:{
        answer:'',
        question:''  
      } , 
      modalLoading:false,
      forms:[] as AQRaq[], 
      chatList: [] as FAQItem[],
      visible:false,
      title:'',
      type:modal.on,
      text:'',
      id:0,
      total:0,
      PAGE_SIZE,
      loading:false,
    }
  },
  methods:{
    // addDomain() {
    //   this.forms.push({
    //     answeer: '',
    //     key: Date.now(),
    //   });
    // },
    handlePaginationChange(current: number){
      this.searchPageReqParams.offset = (current - 1) * this.searchPageReqParams.limit
      this.fetchList()
    },
    query(){
      console.log(this.searchPageReqParams);
    },
    getNewTime(startTime:number,endTime:number){
      this.searchPageReqParams.startTime = startTime
      this.searchPageReqParams.endTime = endTime
    },
    reset(){
      this.searchPageReqParams.startTime = undefined
      this.searchPageReqParams.endTime = undefined  
      this.fetchList()
    },
    addInput(){
      let newList = {
        answer:'',
        question:''
      }
      if(this.forms.length<5){
        this.forms.push(newList)
        // this.forms.splice(index+1,0,newList)  
      }    
    },
    minInput(index:number){
       this.forms.splice(index,1)    
    },
     resetForm() {
      // this.count=1
      // this.form.answer=''
      // this.form.question=''
     let length=this.forms.length
      for(let i=1;i<length;i++){
        this.forms.splice(this.forms.length-1,2) 
      }
      this.forms[0].answer=''
      this.forms[0].question=''
      console.log(this.forms.length);
      
      
      // let form = this.form
      // type formtype = keyof typeof form
      // Object.keys(this.form).forEach(m=>{
      //   this.form[m as formtype] = '' 
      // })
    },
    //发布
    onSubmit() {
      (this.$refs.ruleForm as FormModel).validate(valid => {
        if (valid) {
          this.show = false
          for(let i=0;i<this.forms.length;i++){
            FAQService.getInstance(). AddQueAns({
              answer:this.forms[i].answer,
              question: this.forms[i].question 
              }).then((ret) => {
                if (ret.code === 200) {
                  this.fetchList()
                }
            })
          }
          this.resetForm()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    add(recode:any){
      this.id=recode.id
      this.type = modal.on
      this.visible = true
      this.title = '上架内容'
      this.text = '确定上架该内容吗？'
    },
    remove(recode:any){
      this.id=recode.id
      this.type = modal.off
      this.visible = true
      this.title = '下架内容'
      this.text = '确定下架该内容吗？'
    },
    onDelete(recode:any){
      this.id=recode.id
      this.type = modal.delete
      this.visible = true
      this.title = '删除内容'
      this.text = '确定删除该内容吗？'
    },
    //查询
    async fetchList() {
      const ret = await FAQService.getInstance().CheckQueAnsList({
        end_time: this.searchPageReqParams.endTime as number,
        start_time:  this.searchPageReqParams.startTime as number,
        limit:this.searchPageReqParams.limit,
        faq_status: this.searchPageReqParams.faq_status,
        offset: this.searchPageReqParams.offset,
      })
      
      if (ret.code === 200) {
        // this.chatList = covertItems(ret.data.items) 
        this.chatList = ret.data.items 
        this.total=ret.data.total 
      }        
    },
    //上/下架、删除
    async handleOk(record:any){
      this.loading = true
      console.log(this.id, 'this.id')
      try {
        if( this.type == modal.on){//上架
          await FAQService.getInstance().ModifyQueAns({
            faq_status: eAQRStatus.published,id:this.id
          });
        } else if( this.type == modal.off){//下架
          await FAQService.getInstance().ModifyQueAns({
            faq_status: eAQRStatus.editable,id:this.id
          });
        } else if( this.type == modal.delete){//删除
          await FAQService.getInstance().DeleteQueAns({id:this.id+''});
        }
        this.visible = false
        this.fetchList()
      }catch (err) {}
      
      this.loading = false
    },
    Status(status: number){
      if(status === 2){
        return '已发布'
      }else if(status === 1){
        return '待发布'
      }
    }
  },
  // created(){
  //    chatList.forEach(m=>{
  //       if(m.type == '自动回复')
  //         autoLength
  //     })
  // }
})
</script>
