<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :wrapperFooterOffset="20" destroyOnClose :title="title" width="60%"  @ok="handleSubmit"  @cancel="handleCancel" :centered="true">
    <a-form :model="searchModel" :label-col="labelCol" :wrapper-col="wrapperCol"  layout="inline"  style="width:100%;height:440px">
    <div style="width:100%;background-color:">
      <a-row :gutter="16"  style="width:100%">
        <a-col :span="21">
            <a-row  style="width:100%">
              <a-col :span="9">
                  <vxe-input v-model="searchModel.lableName" type="search"  @change="handleSearch()" clearable placeholder="请输入" style="width:90%;margin-left:5px">
                  </vxe-input>
              </a-col>
              <a-col :span="6">
                <a-form-item label="一级分类">
                    <JSearchSelect placeholder="请输入" v-model:value="searchModel.pclassifyCode"  :allowClear="true"
                    dict="st_classify,classify_name,classify_code,level1='1' and has_child='1' order by sort_no desc" 
                    @change="fSelectChange" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="二级分类">
                    <JSearchSelect placeholder="请输入" v-model:value="searchModel.sclassifyCode" 
                    :allowClear="true"
                    :dict='sDict'
                    @change="fSelectChange2"
                    @click="sSelectClick" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <vxe-button status="primary" @click="handleSearch()">搜索</vxe-button>
              </a-col>
            </a-row>
        </a-col>
        <a-col :span="3">
          <vxe-button status="primary" @click="handleAdd()">新增</vxe-button>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col span="24">
          <div style="margin:10px">
            <blockquote class="info" style="margin:10px 0">
                <a-row :gutter="16" style="width:100%">
                  <a-col span="3">
                    记录数: <a-badge :count="labelDatas.length"/>
                  </a-col>
                  <a-col span="2">
                    <span style="margin-right:0px">已选:</span>
                  </a-col>
                  <a-col span="19">
                    <a-tag v-for="(item,i) in selectTag" :key="item.lableCode" closable @close="handlerTagClose(item)" color="#108ee9">{{ item.lableName }}</a-tag>
                  </a-col>
                </a-row>
            </blockquote>
            <vxe-grid ref="tableRef" v-bind="gridOptions"  :loading="loading" v-on="gridEvents"  
                :row-config="{isCurrent: true, isHover: true}"
                @checkbox-change="setSelectLabels" 
                :column-config = {resizable:true}>
              </vxe-grid>
          </div>
        </a-col>
      </a-row>

      <AuditLableModal @register="registerAddModal" @success="handleSuccess"></AuditLableModal>
    </div>
  </a-form> 

  </BasicModal>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { reactive,ref,nextTick } from 'vue'
import { JSearchSelect } from '/@/components/Form';
import { queryAllLabels,queryActRelates } from '../../index.api';
import AuditLableModal from './AuditLableModal.vue';
import { BasicModal, useModal, useModalInner } from '/@/components/Modal';

const [registerAddModal, {openModal}] = useModal();


const emit = defineEmits(['register', 'success','saveLabel']);

const title = ref("添加标签")
const labelDatas = ref([]);
const tableDatas = ref([])
const loading = ref(false)

const tableRef = ref()

const selectTag = ref([])

const searchModel = reactive({
  lableName:"",
  pclassifyCode:"",
  sclassifyCode:""
});


const isUpdate = ref(true);
const isDetail = ref(false);
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {

    setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;
    loading.value = true
    tableDatas.value = labelDatas.value = await queryActRelates({tp:10});
    loading.value = false

    let ids = data.labelIds;
    if(!ids) return;
    let idAry = ids.split(",")
    
    nextTick(() => {
      setTimeout(()=>{
        const $table =tableRef.value;
        const selRows  = labelDatas.value.filter(item => idAry.includes(item.lableCode));  
        $table.setCheckboxRow(selRows, true)
        selectTag.value = $table?.getCheckboxRecords();

      },100)
    })
})



const labelCol = ref({
      xs: {span: 24},
      sm: {span: 2},
      lg: {span:8}
  })
const wrapperCol = ref({
    xs: {span: 24},
    sm: {span: 6},
    lg: {span:16}
})

const gridOptions = reactive({
  showOverflow: true,
  border: true,
  height: 300,
  checkboxConfig: {
    labelField: 'lableCode',
    highlight: true,
    checkStrictly:true
  },
  columns: [
    {type: 'checkbox', width: 200,title:"标签编号"},
    {field: 'lableName', title: '标签名称', type:"html" },
    {field: 'level1',title: '一级分类', width: "15%"},
    {field: 'level2',title: '二级分类', width: "15%"},
    {field: 'sclassifyCode',title: 'sclassifyCode',visible: false},
    {field: 'pclassifyCode',title: 'pclassifyCode',visible: false},
  ],
  data: labelDatas
})

function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

const sDict = ref('')
function fSelectChange(val){
  searchModel.pclassifyCode=val
  let dit = "st_classify,classify_name,classify_code,level1='2' and upper_classify_code='"+val+"' order by sort_no desc"
  sDict.value = dit
  handleSearch();
}

function fSelectChange2(val){
  searchModel.sclassifyCode=val
  handleSearch();
}
function sSelectClick(){
  if(!searchModel.pclassifyCode){
    message.warning('请先选择一级分类!')
  }
  
}

const handleSearch = () => {
  labelDatas.value = tableDatas.value
  if(searchModel.pclassifyCode) {
    labelDatas.value = tableDatas.value.filter(item => item['pclassifyCode']==searchModel.pclassifyCode)
    if(searchModel.sclassifyCode) {
      labelDatas.value = labelDatas.value.filter(item => item['sclassifyCode']==searchModel.sclassifyCode)
    } 
  } else {
    if(searchModel.sclassifyCode) {
      labelDatas.value = tableDatas.value.filter(item => item['sclassifyCode']==searchModel.sclassifyCode)
    } 
  }
  const filterVal = String(searchModel.lableName).trim().toLowerCase()
  if (filterVal) {
    const filterRE = new RegExp(filterVal, 'gi')
    const searchProps = ['lableName','lableCode','level1','level2']
    labelDatas.value  = labelDatas.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
    //labelDatas.value = rest.map(row => {
      //const item = Object.assign({}, row)
      // searchProps.forEach(key => {
      //   item[key] = String(item[key]).replace(filterRE, match => `<span style="color:red">${match}</span>`)
      // })
     // return item
    // })
  } 
}

function handleSuccess(isUpdate,data) {
  if(isUpdate) {

  } else {
    labelDatas.value.unshift(data);
  }
  
}

function handleSubmit() {
  let lableCode = []
  let lableName = []
  const $table =tableRef.value;
  if ($table) {
    
    selectTag.value.forEach(function (ele) {
      lableCode.push(ele.lableCode)
      lableName.push(ele.lableName)
    })
    selectTag.value=[]
    $table.clearCheckboxRow()
    emit("saveLabel",lableCode,lableName)
    closeModal()
  }
  return null
}

const gridEvents = {
  cellClick ({row, column}) {
    const $table = tableRef.value
    $table.toggleCheckboxRow(row)
    setSelectLabels({row:row});
  }
}


function setSelectLabels(obj) {
  let curRow = obj.row;
  const $table = tableRef.value
  let curSelRows = $table.getCheckboxRecords()
  let curIsExist = selectTag.value.findIndex(item => item.id == curRow.id);
  let isAdd = curSelRows.findIndex(item => item.id == curRow.id);
  if(isAdd>-1) {
    if(curIsExist==-1) {
      selectTag.value.push(curRow)
    }
  } else {
    if(curIsExist>-1) {
      selectTag.value= selectTag.value.filter(item => item.id !== curRow.id);
    }
  }
}

function handlerTagClose(row){
  const $table = tableRef.value
  $table.toggleCheckboxRow(row)
  if(selectTag.value.includes(row)) {
    selectTag.value= selectTag.value.filter(item => item.id !== row.id);
  }
}

function handleCancel() {
  const $table = tableRef.value
  selectTag.value=[]
  $table.clearCheckboxRow()
}


</script>
