<template>
  <el-form class="pl-4 pr-4 pt-4" label-width="85px" label-position="left">
    <el-form-item label="sheet页">
      <el-input v-model="formState.sheetNum" disabled />
    </el-form-item>
    <el-form-item label="行">
      <el-input v-model="formState.rowNum" disabled />
    </el-form-item>
    <template v-if="!getIsSelectedRow">
      <el-form-item label="列">
        <el-input v-model="formState.columNum" disabled />
      </el-form-item>
      <el-form-item label="值">
        <el-input v-model="formState.v" disabled />
      </el-form-item>
      <el-form-item label="单元格属性">
        <el-select v-model="formState.mp">
          <template v-for="group in allFields" :key="group.label">
            <el-option-group :label="group.label">
              <el-option
                v-for="item in group.options"
                :key="item.filedName"
                :label="item.fliedTitle"
                :value="item.filedName"
              >
              </el-option>
            </el-option-group>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="脚本">
        <el-select v-model="formState.scriptName" @change="scriptsChange">
          <template v-for="item in scripts">
            <el-option :value="item.srciptName" :label="item.srciptName"></el-option>
          </template>
        </el-select>
      </el-form-item>
    </template>

    <!-- 脚本配置 -->
    <template v-for="item in scriptsPmList">
      <el-form-item :label="item.fliedTitle">
        <el-input v-model="scriptsParams[item.filedName]"></el-input>
      </el-form-item>
    </template>
  </el-form>

  <div class="flex justify-center">
    <el-button type="primary" @click="saveCellConfig">{{
      getIsSelectedRow ? '设置开始循环体' : '确定标记'
    }}</el-button>
    <el-button v-show="!getIsSelectedRow" type="default" @click="deleteCellMark">删除标记</el-button>
    <el-button type="default" @click="todoAnalysis">执行解析</el-button>
  </div>

  <vxe-modal :z-index="1005" v-model="analysisVisible" width="800">
    <vxe-table size="mini" height="600" border :data="analysisData">
      <template v-for="column in tableColumn" :key="column.filedName">
        <vxe-column :field="column.filedName" :title="column.fliedTitle" width="200"></vxe-column>
      </template>
    </vxe-table>
  </vxe-modal>
</template>

<script lang="ts" setup>
import { ref, watch, unref, reactive, computed, onMounted, toRef, nextTick } from 'vue'
import { useExcelStore } from '@/stores/excel'
import {
  apiClearMark,
  apiDeleteMark,
  apiGetOrderField,
  apiGetScript,
  apiSaveMark,
  apiToDo,
  saveExcelOrderIndex
} from '@/api/excel'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useLuckysheetMark } from '../useLuckysheet'
import { storeToRefs } from 'pinia'

const analysisVisible = ref(false)
const analysisData = ref([])
const props = defineProps<{
  selectedCell: any
  selectedRow: any
}>()
const orderFields = ref<Record<string, any>[]>([])
const variableFields = ref<Record<string, any>[]>([])
const scripts = ref<Record<string, any>[]>([])
const scriptsPmList = ref<Record<string, any>[]>([])
let scriptsParams = ref<Record<string, any>>({})
const formState = reactive({
  filedConfId: '',
  rowNum: '',
  columNum: '',
  v: '',
  mp: '',
  sheetNum: '',
  scriptName: '',
  params: {}
})
const { removeMark, addMark } = useLuckysheetMark()
const excelStore = useExcelStore()
const { resetMarks, deleteMark, setMark, setSheetBegin } = excelStore
const { getFileInfo, getIsSelectedRow, getSheetBegin } = storeToRefs(excelStore)

const allFields = computed(() => {
  return [
    { label: '可变字段', options: variableFields.value },
    { label: '订单字段', options: orderFields.value }
  ]
})

const tableColumn = computed(() => {
  const column = [{filedName: 'productCode', fliedTitle: '产品编码'}]
  const f = allFields.value.map(item => item.options || [])
  f.forEach(item => column.push(...item))
  return column
})

watch(
  [props.selectedCell, props.selectedRow],
  ([cell, row]) => {
    if (getIsSelectedRow.value) {
      formState.rowNum = row.rowNum.join(',')
      formState.sheetNum = row.sheetNum
    } else {
      Object.assign(formState, unref(cell))
      scriptsChange(cell.scriptName)

      if (cell.scriptName && cell.params) {
        Object.assign(unref(scriptsParams), cell.params)
      }
    }
  },
  { deep: true }
)

const deleteCellMark = async () => {
  if (formState.sheetNum === '' || !formState.filedConfId) {
    alert('请选择需要清除标记的单元格！')
    return
  }
  ElMessageBox.confirm('是否确认清除当前选中单元格标记？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await apiDeleteMark(formState.filedConfId)
    // 清除本地mark
    deleteMark(formState.sheetNum, formState.rowNum, formState.columNum)
    // 清除excel标记
    removeMark(unref(formState))
    // 重置formState一些字段
    resetFormState()
  })
}

const resetFormState = () => {
  formState.mp = ''
  formState.scriptName = ''
  scriptsPmList.value = []
  generateScriptPs([])
}

const saveCellConfig = async () => {
  if (getIsSelectedRow.value) {
    const oldBegin = getSheetBegin.value[formState.sheetNum]
    const isAlready = !!oldBegin?.forIndexId
    console.log('oldBegin', oldBegin)

    // 如果设置的循环体开始行是一样，就不执行
    if (oldBegin?.rowNum == formState.rowNum) {
      return
    }

    const params = {
      forIndexId: oldBegin?.forIndexId || '',
      rowNum: props.selectedRow.rowNum[0],
      sheetNum: formState.sheetNum,
      fileId: getFileInfo.value.orderFileId
    }
    const { data } = await saveExcelOrderIndex(params)

    if (data.code != 200) {
      return ElMessage.error('设置失败！')
    }

    // 判断是否已经存在，清除以前的整行样式
    if (isAlready) {
      const oldPo = [oldBegin.rowNum, oldBegin.rowNum, 0, 1]
      window.luckysheet.menuButton.customUpdateFormat(null, 'bg', '#ffffff', ...oldPo)
    }

    setSheetBegin(params.sheetNum, data.result)
    // 设置新的整行背景
    setTimeout(() => {
      const po = [formState.rowNum, formState.rowNum, 0, 1]
      window.luckysheet.menuButton.customUpdateFormat(null, 'bg', '#c7f5d3', ...po)
    }, 100)
  } else {
    const params = {
      fileId: getFileInfo.value.orderFileId,
      filedConfId: formState.filedConfId,
      sheetNum: formState.sheetNum,
      rowNum: formState.rowNum,
      columNum: formState.columNum,
      filed: [...variableFields.value, ...orderFields.value].find(
        (v) => v.filedName === formState.mp
      ),
      content: '',
      fileIndex: 0,
      scriptName: formState.scriptName,
      params: unref(scriptsParams),
      formart: ''
    }

    const { data } = await apiSaveMark(params)
    setMark(formState.sheetNum, formState.rowNum, formState.columNum, data.result)
    addMark(data.result)
  }
}
const todoAnalysis = () => {
  ElMessageBox.confirm('是否确认标注完毕，且正确标注？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      apiToDo(getFileInfo.value.orderFileId).then(({data}) => {

        if (data?.code !== 200) {
          ElMessage.error('解析失败！')
          return
        }
        analysisVisible.value = true
        analysisData.value = data.result
      })
      // axios
      //   .get('/api/excel/todo', {
      //     params: { fileId: props.file.orderFileId },
      //     headers
      //   })
      //   .then(({ data }) => {
      //     emit('analysis', data.result)
      //   })
    })
}

/**
 * 切换脚本字段
 * @param {String} e
 * @returns
 */
const scriptsChange = (e: any) => {
  // 如果选择的脚本字段为空，清除参数列表和脚本参数
  if (e === '') {
    scriptsPmList.value = []
    generateScriptPs([])
    return
  }
  const s: any = scripts.value.find((v) => v.srciptName === e)

  if (s.paramsName !== null && s.paramsName?.length) {
    scriptsPmList.value = s.paramsName
    generateScriptPs(s.paramsName)
  } else {
    scriptsPmList.value = []
    generateScriptPs([])
  }
}

/**
 * 生成脚本表单字段
 * @param {Object} ps
 */
const generateScriptPs = (ps: any) => {
  const o: Record<string, any> = {}

  ps.forEach((p: any) => {
    o[p.filedName] = ''
  })
  scriptsParams.value = o
}

const getScript = async () => {
  const { data } = await apiGetScript()
  scripts.value = data.result
}

const getOrderField = async () => {
  const { data } = await apiGetOrderField()
  orderFields.value = data.result
}

onMounted(() => {
  getScript()
  getOrderField()
})
</script>
<style lang="scss" scoped></style>
