<script>
import XFormTable from '@vue2-client/base-client/components/common/XFormTable'
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'
import { mapState } from 'vuex'
export default {
  components: {
    XFormTable
  },
  expose: ['setFormShow'],
  watch: {
    'form.f_address_type' (newVal, oldVal) {
      this.onAddressTypeChange(newVal, oldVal)
    }
  },
  mounted () {
    this.getAreaList('')
  },
  data () {
    return {
      selectAddressVisible: false,
      addAddressFlag: false,
      confirmLoading: false,
      form: {
        f_address_type: '',
        f_residential_area_id: '',
        f_residential_area: '',
        f_iscity: ''
      },
      addressModel: [
        {
          expression: '{f_building}楼号{f_unit}单元{f_floor}楼层{f_room}门牌号',
          label: '城市',
          value: '城市'
        },
        {
          expression: '{f_building}组{f_unit}号',
          label: '乡镇',
          value: '乡镇'
        },
        {
          expression: '{f_address}',
          label: '自定义',
          value: '自定义'
        }
      ],
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      formItems: [],
      areaList: [],
      signContractVisible: false
    }
  },
  methods: {
    setFormShow () {
      this.selectAddressVisible = true
    },
    selAddress (record) {
      // 给表单赋值
      const form = {
        f_address: record.tua_f_address,
        f_address_id: record.tua_id
      }
      console.log('选择了地址是', form)
      this.$emit('setAddress', form)
      this.selectAddressVisible = false
    },
    addAddress () {
      // 获取地址模式配置
      getConfigByName('addressTypeDic', 'af-revenue', (res) => {
        // 地址模式赋值
        if (res.value?.length) {
          this.addressModel = res.value
        }
        // 赋值默认地址模式
        this.form = { f_address_type: this.addressModel[0].value }
        this.addAddressFlag = true
        this.addAddressMsg = '添加地址'
        this.onAddressTypeChange()
      })
    },
    onAddressTypeChange (newVal, oldVal) {
      const selectedModel = this.addressModel.find(item => item.value === this.form.f_address_type)
      Object.keys(this.form).forEach(key => {
        if (key.endsWith('_suffix')) {
          this.form[key] = ''
        }
      })
      if (selectedModel) {
        const matches = selectedModel.expression.match(/{(.*?)}([^{}]*)(?={|$)/g)
        this.formItems = matches.map(item => {
          const value = item.match(/{(.*?)}/)[1]
          const label = item.replace(/{.*?}/, '').trim()
          // 处理后缀
          this.form[`${value}_suffix`] = label
          return {
            label: label || (value === 'f_address' ? '' : value), // 如果存在后面的文字，就使用后面的文字作为 label，否则使用原来的值
            value: `${value}`
          }
        })
      }
    },
    handleSearch (value) {
      this.getAreaList(value)
    },
    getAreaList (value) {
      console.log('搜索小区', this.currUser)
      runLogic('getAreaListByName', {
        orgId: this.currUser.orgid,
        name: value
      }, 'af-revenue').then(res => {
        console.log(res)
        this.areaList = res
      })
    },
    handleChange (value) {
      this.form.f_residential_area = this.areaList.find(item => item.value === value).label
      console.log(this.form.f_residential_area)
    },
    addressSubmit () {
      if (!this.form.f_residential_area) {
        this.$message.warning('请选择小区')
        return
      }
      this.confirmLoading = true
      try {
        this.deleteAddressData()
        runLogic('addAddress', Object.assign({}, this.form, {
          f_address: this.generateAddressString()
        }, {
          orgid: this.currUser.orgid,
          f_orgid: this.currUser.orgid,
          f_orgname: this.currUser.orgs,
          f_depid: this.currUser.depids,
          f_depname: this.currUser.deps,
          f_operatorid: this.currUser.id,
          f_operator: this.currUser.name,
          f_filialeid: this.currUser.orgid
        }), 'af-revenue').then(res => {
          if (res) {
            this.$message.success(`${this.addAddressMsg}成功`)
          }
        }).catch(() => {
          this.$message.error('添加地址失败')
        }).finally(() => {
          this.confirmLoading = false
          this.addAddressFlag = false
          this.$refs.selAddressXFormTable.refreshTable(true)
        })
      } catch (error) {
        this.$message.error('添加地址失败')
        this.confirmLoading = false
        this.addAddressFlag = false
      }
    },
    // 删除 addressData 中存在 addressModel 不存在的字段
    deleteAddressData () {
      // 目前只需要检查这几个key
      const keys = ['f_building', 'f_unit', 'f_floor', 'f_room']
      Object.keys(this.form).forEach(key => {
        if (keys.includes(key) && !this.formItems.some(item => item.value === key)) {
          this.form[key] = ''
          this.form[`${key}_suffix`] = ''
        }
      })
    },
    generateAddressString () {
      const selectedModel = this.addressModel.find(item => item.value === this.form.f_address_type)
      if (selectedModel) {
        let addressString = selectedModel.expression
        this.formItems.forEach(item => {
          const value = this.form[item.value]
          addressString = addressString.replace(`{${item.value}}`, value)
        })
        return addressString
      }
      return ''
    },
  },
  computed: {
    inputWidth () {
      if (this.formItems.length === 1) {
        return '85%'
      }
      return this.formItems.length ? `${65 / this.formItems.length}%` : '85%'
    },
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', { isMobile: 'isMobile' })
  },
}

</script>

<template>
  <div>
    <!-- 地址弹出框 -->
    <a-modal
      v-model="selectAddressVisible"
      :dialog-style="{ top: '30px' }"
      :bodyStyle="{height:'80vh',overflowY:'scroll'}"
      :destroy-on-close="true"
      :z-index="1002"
      title="选择地址"
      :footer="null"
      width="80vw">
      <x-form-table
        title="选择地址"
        queryParamsName="userfiles_sel_address"
        @action="selAddress"
        serviceName="af-revenue"
        :extraHeight="225"
        ref="selAddressXFormTable">
        <template #leftButton="{selectedRows}">
          <a-button
            type="primary"
            :disabled="selectedRows?.length !== 1"
            @click="selAddress(selectedRows[0])"> 选择地址</a-button>
          <a-button
            type="primary"
            @click="addAddress"> 新建地址
          </a-button>
        </template>
      </x-form-table>
    </a-modal>
    <!--  添加地址  -->
    <a-modal
      v-model="addAddressFlag"
      :dialog-style="{ top: '30px' }"
      :z-index="1005"
      @ok="addressSubmit"
      :ok-button-props="{ loading: confirmLoading }"
      :confirm-loading="confirmLoading"
      @cancel="addAddressFlag = false"
      title="新增地址信息"
      :destroyOnClose="true">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="小区">
          <a-select
            show-search
            placeholder="请选择小区"
            option-filter-prop="children"
            @search="handleSearch"
            style="width: 200px"
            @change="handleChange"
          >
            <a-select-option v-for="item in areaList" :value="item.value" :key="item">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="地址类型">
          <a-radio-group v-model="form.f_address_type">
            <a-radio :value="item.value" v-for="(item, index) in addressModel" :key="index">
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="详细地址">
          <div v-for="(item, index) in formItems" :key="index" style="display: inline;white-space: nowrap">
            <a-input v-model="form[item.value]" style="display: inline;" :style="{ width: inputWidth }"/>
            <span>{{ item.label }}</span>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<style>

</style>
