<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">变量转换</p>
    <el-form class="pt-4" :inline="true" :model="queryParams">
      <el-form-item label="模版文件ID">
        <el-input v-model="queryParams.templateFileId" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="queryParams.customerId_dict" placeholder="" readonly>
          <template #append>
            <el-button :icon="MoreFilled" @click="visibleModal = true"></el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="产品编码">
        <el-input v-model="queryParams.productCode" placeholder="产品编码"></el-input>
      </el-form-item>
      <!-- <el-form-item label="产品">
        <el-input v-model="queryParams.productId_dict" readonly placeholder="产品名称" clearable>
          <template #append>
            <el-button :icon="MoreFilled" @click="" />
          </template>
        </el-input>
      </el-form-item> -->
      <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="" clearable>
          <template v-for="item in statusOptions">
            <el-option :value="item.value" :label="item.label"></el-option>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="default" @click="onReset">重置</el-button>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="">
      <vxe-table
        ref="xTable"
        size="small"
        min-height="460"
        show-overflow="tooltip"
        border
        :loading="loading"
        :data="tableData"
      >
        <vxe-column field="templateFileId" title="模版文件ID" width="200">
          <template #default="{ row }">
            <el-link
              target="_blank"
              :href="'/preview-excel?fileId=' + row.templateFileId + '&type=var'"
              >{{ row.templateFileId }}</el-link
            >
          </template>
        </vxe-column>
        <vxe-column field="customerId_dictText" title="客户" width="300"></vxe-column>
        <vxe-column field="productCode" title="产品编码" width="300"></vxe-column>
        <vxe-column field="status_dictText" title="订单状态" width="120"></vxe-column>
        <vxe-column field="createTime" title="创建时间" width="160"></vxe-column>
        <vxe-column field="action" title="操作" min-width="250">
          <template #default="{ row }">
            <el-link style="font-size: 12px" type="primary" @click="toDetail(row)">查看</el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link class="ml-1" style="font-size: 12px" type="primary" @click="confirmChange(row)"
              >转换</el-link
            >
            <el-divider direction="vertical"></el-divider>
            <el-link
              class="ml-1"
              style="font-size: 12px"
              type="primary"
              @click="showDetail(row, 'old')"
              >转换前</el-link
            >
            <el-divider direction="vertical"  v-if="row.status == 'converted' || row.status == 'confirm'"></el-divider>
            <el-link
              class="ml-1"
              style="font-size: 12px"
              type="primary"
              v-if="row.status == 'converted' || row.status == 'confirm'"
              @click="showDetail(row, 'new')"
              >转换后</el-link
            >
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager
        size="small"
        background
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :total="queryParams.total"
        @page-change="onQuery"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
      >
      </vxe-pager>
    </div>
  </div>

  <vxe-modal
    v-if="detailVisible"
    v-model="detailVisible"
    title="解析详情"
    width="80%"
    show-footer
    @hide="detailHide"
  >
    <vxe-table
      border
      size="mini"
      height="500"
      show-overflow="tooltip"
      show-header-overflow="tooltip"
      :data="detailTable"
    >
      <vxe-column title="行号" width="120" key="行号">
        <template #default="{ row }">{{ row.sortNum }}</template>
      </vxe-column>
      <vxe-column title="数据区" width="120" key="数据区">
        <template #default="{ row }">{{ row['数据区'] }}</template>
      </vxe-column>

      <vxe-column title="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" plain @click="copyOrders(row)">复制变量</el-button>
        </template>
      </vxe-column>

      <!-- 查看状态下直接显示 -->
      <!-- <template v-if="currentRow.status == 'un_confirm'">
        <vxe-column
          v-for="item in tableTitle"
          :key="item"
          :title="item"
          :field="item"
          width="200"
        />
      </template> -->

      <!-- 转换下使用 -->
      <template>
        <vxe-colgroup v-for="item in tableTitle" :key="item" :title="item">
          <vxe-colgroup>
            <template #header>
              <div class="header-cell" @click="(e) => showPopover(e, item)">
                
                <el-tooltip v-if="showScriptNumber(getAllMapConfigs[item].filedConfs) !=0" class="item" effect="dark" 
                :content="showScriptNames(getAllMapConfigs[item].filedConfs)" placement="top-start">
                   <el-button type="danger" size="small" circle>{{ showScriptNumber(getAllMapConfigs[item].filedConfs) }}</el-button>
                </el-tooltip>

                <template v-for="cf in getAllMapConfigs[item].filedConfs">
                  <span>{{ cf.orderFiled?.fliedTitle }}</span>
                </template>
                <el-icon><Setting /></el-icon>
              </div>
            </template>
            <vxe-column :title="item" :field="item" width="200" :key="item">
              <template #header>
               <div class="header-cell" @click="(e) => showPopover(e, item)">
                <el-tooltip v-if="showFilterScriptNumber(getAllMapConfigs[item].filedConfs) !=0" class="item" effect="dark" 
                :content="showFilterScriptNames(getAllMapConfigs[item].filedConfs)" placement="top-start">
                   <el-button type="danger" size="small" circle>{{ showFilterScriptNumber(getAllMapConfigs[item].filedConfs) }}</el-button>
                </el-tooltip>

                <template v-for="cf in getAllMapConfigs[item].filedConfs">
                  <span>{{ cf.filterFiled?.fliedTitle }}</span>
                </template>
                  <el-icon><Setting /></el-icon>
                </div>

              </template>
            </vxe-column>
          </vxe-colgroup>
        </vxe-colgroup>
      </template>
    </vxe-table>

    <el-popover
      ref="popoverRef"
      placement="bottom"
      :virtual-ref="buttonRef"
      trigger="click"
      :title="currentConfigTitle"
      :visible="popoverVisible"
      virtual-triggering
      width="400"
      transition=""
    >
      <ConfigForm
        :title="currentConfigTitle"
        :current-conf="currentColConf"
        :current-row="currentRow"
        @cancel="popoverVisible = false"
        @confirm="confirmConfig"
      />
    </el-popover>

    <template #footer>
      <el-button type="primary" @click="onCopy">复制</el-button>
      <el-button type="primary" v-if="isCopying" @click="onPaste">引入</el-button>
      <!-- <el-button @click="confirmChange" v-if="currentRow.status == 'un_convert'">确认转换</el-button> -->
      <el-button @click="saveOrderField" type="primary">保存</el-button>
    </template>
  </vxe-modal>

  <CustomerModal v-model:visible="visibleModal" @confirm="confirmCustomer" />
  <TemplateVariable v-model:visible="tempVisible" v-bind="details" />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
import { Setting, MoreFilled } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash-es'
import {
  apiVarTemplatePage,
  apiVarTemplateGetVars,
  apiVarTemplateGetNewVars,
  apiVarTemplateGetConf,
  apiVarTemplateConvert,
  apiVarTemplateSaveConf,
  getVarSpecList,
  getFilterMapField
} from '@/api/var'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import type { Recordable } from '@/types/global'
import { filterRunData2 } from '@/utils/excel'
import { apiDictList } from '@/api/common'
import ConfigForm from './components/ConfigForm1.vue'
import { useVariableExcelChangeStore } from '@/stores/excel'
import { storeToRefs } from 'pinia'
import TemplateVariable from './components/TemplateVariable.vue'
import { useOrderChangeCopy } from '@/hooks/useOrderChangeCopy'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'

const visible = ref(false)
const loading = ref(false)
const importVisible = ref(false)
const excelChangeStore = useVariableExcelChangeStore()
const { getAllMapConfigs } = storeToRefs(excelChangeStore)
const { copyInfo, isCopying, handleCopy } = useOrderChangeCopy()

/**查询参数 */
const queryParams = reactive({
  status: '',
  templateFileId: '',
  productCode: '',
  productId: '',
  productId_dict: '',
  customerId: '',
  customerId_dict: '',
  currentPage: 1,
  pageSize: 10,
  total: 0,
  column: 'createTime',
  order: 'desc'
})

const currentColConf = reactive({
  excelOrderFiledConfId: '',
  title: '',
  filedConfs: [],
  templateFileId: ''
})
const currentConfigTitle = ref('')

const visibleModal = ref(false)
const xTable = ref<VxeTableInstance>()
const tableData = ref([])
/**当前选择行 */
const currentRow = reactive<Recordable>({})
/**弹窗显示 */
const detailVisible = ref(false)
/**详情表格数据 */
const detailTable = ref<Recordable[]>([])
/**表格title */
const tableTitle = ref<string[]>([])

const statusOptions = ref([])

const queryDict = async (code: string) => {
  const { data } = await apiDictList({
    dictCodes: code
  })
  statusOptions.value = data.result[code]
}

const popoverRef = ref()
const buttonRef = ref()
const popoverVisible = ref(false)
const showPopover = (e: any, title: string) => {

  buttonRef.value = e.target
  // 设置标题
  currentConfigTitle.value = title
  const hasConf = !!getAllMapConfigs.value[title].filedConfs.length
  const conf = hasConf
    ? getAllMapConfigs.value[title]
    : {
        excelOrderFiledConfId: '',
        title,
        filedConfs: [
          {
            mapField: '',
            orderFiled: null,
            scripts: [],
            filterMapFiled: null,
            filterScripts: [],
            filterFiled: null
          }
        ],
        templateFileId: currentRow.templateFileId
      }
  Object.assign(currentColConf, conf)
  // 打开popover
  popoverVisible.value = true
}

/**监听popover和modal显示状态。重置表单信息 */
watch([detailVisible, popoverVisible], (val) => {
  // 关闭弹窗或者关闭popover
  if (val.includes(false)) {
    // 解决关闭弹窗之后，popover未关闭情况
    popoverVisible.value = false
  }
})

/** 确认字段映射及脚本的配置 */
const confirmConfig = (configList: any) => {
  // 便利一下是否有变量字段
  excelChangeStore.setSingleFieldMap({
    ...currentColConf,
    filedConfs: cloneDeep(
      configList
        .map((item) => {
          if (item.mapField) {
            item.orderFiled = {
              fliedTitle: item.mapField,
              filedName: item.mapField,
              variable: true
            }
          }
          // 没有选择过滤字段时
          if (!item.filterFiled) {
            item.filterMapFiled = null
            item.filterScripts = []
            item.filterFiled = null
          }
          return item
        })
        .filter((v) => !!v.mapField || !!v.filterMapFiled)
    )
  })
  // 关闭popover
  popoverVisible.value = false
}

const confirmCustomer = (list: any) => {
  const [item] = list
  if (!item) return
  queryParams.customerId = item.customerId
  queryParams.customerId_dict = item.customerName
}

const detailHide = () => {
  // detailVisible.value = false;
  detailTable.value = []
  tableTitle.value = []
}


const showScriptNames =  (array) => {
  let value = array?array.map(item => item.scripts.map(scrip=> scrip.scriptName)).join('\n'):''
  return value
}

// const showScriptNumber =  (array) => {

//   let value = 0;
//   let arr = array.map(item =>{
//     value += item.scripts.length
//         // item.scripts.filter(Boolean)
//   });
//   return value
// }

const showScriptNumber =  (array) => {
  let arr = []
  let value = 0;
  if(array){
      console.log("过滤前",array)
      let val =  array.map(item=> item.scripts.map(scrip=> scrip.scriptName))
      val.forEach(item=>{
          console.log("item=",item)
          item.forEach(v=>{
            arr.push(v)
          })
      })
     let val1 = arr.filter(item => item&&item!='')
    value = val1.length
  } 
  return value
}





const showFilterScriptNames =  (array) => {
  let value = array?array.map(item => item.filterScripts.map(scrip=> scrip.scriptName)).join('\n'):''
  return value
}

const showFilterScriptNumber =  (array) => {
   let value = 0;
   array.map(item =>{
    item.filterScripts.map(scrip=>{
      if(scrip&&scrip.scriptName&&scrip.scriptName!=='') {
        value++
      }
    })
   
  });
  return value
}

/**保存订单字段 */
const saveOrderField = async () => {
  const params = {
    templateFileId: currentRow.templateFileId,
    confs: Object.values(getAllMapConfigs.value).filter(
      (v) => v.title !== '' && !!v.filedConfs.length
    )
  }

  apiVarTemplateSaveConf(params).then(({ data }) => {
    if (data.code == 200) {
      ElMessage.success(data.message || '保存成功！')
    } else {
      ElMessage.error(data.message || '保存失败！')
    }
  })
}


const copyOrders = (item)=>{
    
  let arr = []
  for (let key in item) {
    arr.push({
      title:key,
      value: item[key]
    })
   
  }
  const text = JSON.stringify(arr);
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position = "absolute";
  textarea.style.opacity = "0";
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage({
          type: 'success',
          message: '复制变量数据到粘贴板'
        })
}

/** 确认订单转换 */
const confirmChange = async (row) => {
  await ElMessageBox.confirm('是否确认变量转换？', '提示', {
    confirmButtonText: '转换',
    cancelButtonText: '取消',
    type: 'warning'
  })
  loading.value = true
  const { data } = await apiVarTemplateConvert(row.varTemplateDetailId)
  console.log(data)
  loading.value = false
  if (data.code == 200) {
    ElMessage.success(data.message || '转换成功！')
    detailVisible.value = false
    onQuery()
    return
  }
  ElMessage.error(data.message || '转换失败！')
}

const toDetail = async (row: any) => {
  Object.assign(currentRow, row)

  const { data } = await apiVarTemplateGetVars(row.varTemplateDetailId)
  const { data: cdata } = await apiVarTemplateGetConf(row.varTemplateDetailId)
  const { data: specData } = await getVarSpecList(row.productCode)
  // 获取过滤字段
  const { data: filterData } = await getFilterMapField()

  const { res, titles, configs } = filterRunData2(data.result, true)

  excelChangeStore.setSpecList(specData.result)
  excelChangeStore.setFilterMapField(filterData.result)

  cdata.result?.forEach((item) => {
    try {
      Reflect.set(configs[item.title], 'filedConfs', item.filedConfs)
     } catch {
        alert("字段配置异常，请重新配置！否则可能无法进行解析")
     }
   
  })

  // 排除通过循环不显示的column
  const excludeTitles = ['sortNum', '数据区', 'expendData']
  detailTable.value = res
  tableTitle.value = titles.filter((v) => !excludeTitles.includes(v))
  nextTick(() => {
    detailVisible.value = true
  })

  excludeTitles.forEach((key) => {
    Reflect.deleteProperty(configs, key)
  })

  excelChangeStore.setAllMapConfigs(configs)
}

const tempVisible = ref(false)
const details = ref({
  title: '',
  data: [],
  titles: []
})
const showDetail = async (row: any, type = 'old') => {
  loading.value = true
  const { data } =
    type == 'old'
      ? await apiVarTemplateGetVars(row.varTemplateDetailId)
      : await apiVarTemplateGetNewVars(row.varTemplateDetailId)

  const { res, titles, configs } = filterRunData2(data.result, true)
  details.value.title = type == 'old' ? '转换前的变量' : '转换后变量'
  details.value.data = res
  details.value.titles = titles
  loading.value = false
  tempVisible.value = true
}

const onCopy = () => {
  const confs = Object.values(getAllMapConfigs.value).filter(
    (v) => v.title !== '' && !!v.filedConfs.length
  )

  handleCopy(confs)
}

const onPaste = () => {
  // 将复制的配置信息，一条一条设置
  copyInfo.value.forEach((item: any) => {
    item.templateFileId = currentRow.templateFileId
    item.varFiledConfId = ''
    excelChangeStore.setSingleFieldMap(item)
  })

  // 自动保存
  saveOrderField()
}

const onReset = () => {
  queryParams.productCode = ''
  queryParams.status = ''
  queryParams.customerId = ''
  queryParams.customerId_dict = ''
  queryParams.templateFileId = ''
}
const onQuery = async () => {
  loading.value = true
  try {
    const { data } = await apiVarTemplatePage(queryParams)
    tableData.value = data.result.records
    queryParams.total = +data.result.total
  } catch {}
  loading.value = false
}

onMounted(() => {
  onQuery()
  queryDict('excel_order_status')
})
</script>
<style lang="scss" scoped>
.header-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 178px;
}
.expandTableHeader {
  background: #e8eaec;
}
</style>
