import { getRegionCascaderTree } from '@/api/agri/region'
import {
  REGION_CASCADER_PROPS,
  findRegionPath as findRegionPathInTree,
  getRegionNamesByCodes as getRegionNamesByCodesInTree,
  findRegionNodeByCodes as findRegionNodeByCodesInTree,
  parseRegionSelection
} from '@/utils/region'

/**
 * 省市区 el-cascader 混入：loadRegionTree、回显、落库。
 * 页面需提供 this.form；调用 syncRegionCascaderFromForm 时传入字段映射。
 */
export default {
  data() {
    return {
      regionTree: [],
      regionTreeLoaded: false,
      regionCascaderProps: REGION_CASCADER_PROPS
    }
  },
  methods: {
    /** 加载规范化后的省市区树（全局缓存一次） */
    loadRegionTree() {
      if (this.regionTreeLoaded) {
        return Promise.resolve(this.regionTree)
      }
      return getRegionCascaderTree().then(tree => {
        this.regionTree = tree || []
        this.regionTreeLoaded = true
        return this.regionTree
      }).catch(() => {
        this.regionTree = []
        return this.regionTree
      })
    },
    findRegionPath(nodes, targetCode, path) {
      return findRegionPathInTree(nodes || this.regionTree, targetCode, path)
    },
    getRegionNamesByCodes(codes) {
      return getRegionNamesByCodesInTree(this.regionTree, codes)
    },
    findRegionNodeByCodes(codes) {
      return findRegionNodeByCodesInTree(this.regionTree, codes)
    },
    /**
     * 编辑回显：把库里的区县 code 转成 cascader 路径
     * @param {Array<{ codeKey: string, cascaderKey: string }>} fields
     */
    syncRegionCascaderFromForm(fields) {
      if (!this.form || !this.regionTree.length) {
        return
      }
      const list = fields || []
      list.forEach(item => {
        const code = this.form[item.codeKey]
        if (code) {
          this.form[item.cascaderKey] = this.findRegionPath(this.regionTree, code) || []
        }
      })
    },
    /**
     * 级联变更落库：code=区县 code，name=省/市/区县用 / 连接
     * @param {Array} codes cascader 选中路径
     * @param {string} prefix 如 reg / biz → regRegionCode、regRegionName
     */
    applyRegionSelection(codes, prefix) {
      const codeKey = prefix + 'RegionCode'
      const nameKey = prefix + 'RegionName'
      const cascaderKey = prefix + 'RegionCascader'
      const result = parseRegionSelection(this.regionTree, codes)
      if (!codes || !codes.length) {
        this.form[codeKey] = undefined
        this.form[nameKey] = undefined
        return
      }
      if (!result.valid) {
        this.$modal.msgWarning('请选择完整的省/市/区县')
        this.$nextTick(() => {
          this.form[cascaderKey] = []
          this.form[codeKey] = undefined
          this.form[nameKey] = undefined
        })
        return
      }
      this.form[codeKey] = result.code
      this.form[nameKey] = result.name
    }
  }
}
