<template>
  <!-- 所在路段选择弹层 -->
  <SuperTableSelectorDialog
    ref="superTableSelectorDialog"
    :defaultTreeExpandLevel="4"
    :isShow.sync="isShowDialog"
    :isShowSelect="false"
    :isShowTree="false"
    :search-option="optionList"
    :table-data="tableData"
    :table-loading="tableLoading"
    :table-options="tableOptions"
    :tableParams="params"
    :tree-item="treeItem"
    :treeData="orgData"
    :treeTabList="['行政维度']"
    hintLanguage="提示：请在列表中选择路损项目后，点击确认。"
    isSingleChoice
    select-title-name="路损项目明细"
    selectKey="propertySubjectId"
    selectLabel="roadName"
    title="路损项目选择"
    v-bind="$attrs"
    width="75%"
    @closed="closed"
    @open="open"
    @tableRefresh="getTableData"
    @treeChange="treeChange"
    v-on="$listeners"
  />
</template>

<script>
import {tableData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadDamageProjectDetails'
import {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import SuperTableSelectorDialog from '@/components/SuperTableSelectorDialog/index.vue'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'EventChoiceDialog',
  components: {SuperTableSelectorDialog},
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    roadId: {
      default: '',
      type: String
    },
    fatherId: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      orgData: [], // 组织树
      optionList: [
        {
          title: '项目明细名称、编码',
          prop: ['subjectName', 'subjectCode'],
          type: 'input',
          default: true
        },
        {
          title: '项目明细类型',
          prop: 'typeId',
          type: 'select',
          option: getDictionaryByCode('lsxmlx'),
          multiple: true
        },
        {title: '计费单位', prop: 'unit', type: 'input'}
      ],
      tableOptions: [
        {label: '项目明细', minWidth: '30', prop: 'propertySubjectName'},
        {
          label: '项目明细类型',
          minWidth: '50',
          prop: 'typeId',
          formatter: ({typeId}) => dictionaryEscape('lsxmlx', typeId) || '-'
        },
        {
          label: '规格型号',
          minWidth: '40',
          prop: 'model',
          formatter: ({model}) => model || '-'
        },
        {
          label: '收费单价',
          minWidth: '45',
          prop: 'minPrice',
          formatter: row => this.formatPrice(row)
        },
        {label: '计费单位', minWidth: '40', prop: 'unit'},
        {label: '所属区域', minWidth: '50', prop: 'orgName'}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {
            group: 'subjectNameCode',
            operation: 'LIKE',
            relation: 'OR',
            property: 'subjectName'
          },
          {
            group: 'subjectNameCode',
            operation: 'LIKE',
            relation: 'OR',
            property: 'subjectCode'
          },
          {operation: 'IN', property: 'typeId'},
          {operation: 'LIKE', property: 'unit'},
          {operation: 'IN', property: 'orgId'}
        ],
        sorter: [{direction: '', property: 'typeId'}]
      },
      tableData: [], // 所在路段数据
      treeItem: {}, // 树选中
      tableLoading: false // 表格loading
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  created() {
    // this.getOrgTreeData()
  },
  methods: {
    // 打开弹层时触发
    open() {
      // setQueryValue(this.params, 'roadSegmentId', this.roadId || '')
      this.$nextTick(() => {
        this.params.querys[4].value = [this.roadId, this.fatherId]
        this.getTableData()
      })
    },

    // 关闭弹层触发
    closed() {
      const {orgData} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {orgData})
      this.treeItem = this.orgData[0] || {}
      setQueryValue(this.params, 'orgId', this.treeItem?.id || '')
    },

    formatPrice(row) {
      if (row.minPrice && row.maxPrice) {
        if (row.minPrice === row.maxPrice) {
          return row.minPrice + ' 元'
        }
        return `${row.minPrice + ' 元'} - ${row.maxPrice + ' 元'}`
      } else if (row.minPrice) {
        return row.minPrice + ' 元'
      } else if (row.maxPrice) {
        return row.maxPrice + ' 元'
      } else {
        return '-'
      }
    },

    // 获取公司树
    // async getOrgTreeData() {
    //   const {state, value = []} = await getTree()
    //   this.orgData = this.transformTreeData(value)
    //   this.treeItem = this.orgData[0] || {}
    //   let array = []
    //   if (this.treeItem.children.length > 0) {
    //     array = this.treeItem.children.map(item => item.id)
    //     array.push(this.treeItem.id)
    //   }
    //   setQueryValue(this.params, 'orgId', array)
    // },

    // transformTreeData(data) {
    //   return data.map(item => ({
    //     id: item.id,
    //     name: item.name, // 一级目录的 label
    //     children: item.roadList.map(grid => ({
    //       id: grid.id,
    //       name: grid.name, // 二级目录的 label
    //       path: grid.path
    //     }))
    //   }))
    // },

    //获取所在路段列表数据
    async getTableData() {
      this.tableData = []
      this.tableLoading = true
      const {total = 0, rows = []} = await tableData(
        refineRequestBody(this.params)
      )
      this.params.pageBean.total = total
      this.tableData = rows.map(i => {
        const {
          id: propertySubjectId,
          subjectName: propertySubjectName,
          model,
          minPrice,
          maxPrice,
          unit,
          orgName,
          typeId
        } = i
        return {
          propertySubjectId,
          propertySubjectName,
          model,
          minPrice,
          maxPrice,
          unit,
          orgName,
          typeId
        }
      })
      this.tableLoading = false
    },
    confirm() {
      const {
        propertySubjectId,
        propertySubjectName
      } = this.$refs.superTableSelectorDialog.getSelectData()
      this.$emit('confirm', {propertySubjectId, propertySubjectName})
      this.isShowDialog = false
    },
    // 树改变
    treeChange(nodeItem) {
      // 判断是否是一级目录（有 children 属性）
      if (nodeItem.children && nodeItem.children.length > 0) {
        const array = nodeItem.children.map(item => item.id)
        array.push(nodeItem.id)
        setQueryValue(this.params, 'orgId ', array)
      } else {
        setQueryValue(this.params, 'orgId ', [nodeItem?.id] || [])
      }
      // 修改对应的字段值
      // setQueryValue(this.params, 'orgId', treeItem?.id || '')
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped></style>
