<template>
  <SelectItemModal :show-checkbox-drawer="showCheckboxDrawer" @closeDrawer="closeCheckBoxDrawer" :list="accountList"
    v-model="customerFormData.bizman_id" />
  <view class="example">
    <!-- 展示不同的排列方式 -->
    <uni-forms ref="customerFormRef" :modelValue="customerFormData" :rules="rules" validateTrigger="submit" label-position="top">
      <uni-forms-item label="客户名称" required label-width="90px" name="name">
        <uni-easyinput v-model="customerFormData.name" placeholder="请输入客户名称" />
      </uni-forms-item>
      <uni-forms-item label="客户行业" required label-width="90px" name="industry_id">
        <uni-data-select v-model="customerFormData.industry_id" :localdata="industryList" 
          placeholder="请选择客户行业"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item label="客户级别" required label-width="90px" name="level_id">
        <uni-data-select v-model="customerFormData.level_id" :localdata="customerLevelList" 
          placeholder="请选择客户级别"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item label="所在地区" required label-width="90px" name="region_id">
        <view class="custom-select-class" @click="showRegionModal">
          <view class="custom-select-content">
            <text v-if="customerFormData.region_id">{{ customerFormData.region_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择客户所在地区</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;color:#909399;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="客户联系人" label-width="90px" name="link_man">
        <uni-easyinput v-model="customerFormData.link_man" placeholder="请输入客户联系人" />
      </uni-forms-item>
      <uni-forms-item label="联系电话" label-width="90px" name="link_phone">
        <uni-easyinput v-model="customerFormData.link_phone" placeholder="请输入联系电话" />
      </uni-forms-item>
      <uni-forms-item label="经营地址" label-width="90px" name="address">
        <uni-easyinput v-model="customerFormData.address" placeholder="请输入客户经营地址" />
      </uni-forms-item>
      <uni-forms-item label="市场负责人" label-width="90px" name="bizman_id">
        <view class="custom-select-class" @click="showCheckBoxDrawer">
          <view class="custom-select-content">
            <text v-if="customerFormData.bizman_id">{{ customerFormData.bizman_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择市场负责人</text>
          </view>

          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="发票抬头" label-width="90px" name="invoice_title">
        <uni-easyinput v-model="customerFormData.invoice_title" placeholder="请输入发票抬头" />
      </uni-forms-item>
      <uni-forms-item label="客户税号" label-width="90px" name="tax_no">
        <uni-easyinput v-model="customerFormData.tax_no" placeholder="请输入客户税号" />
      </uni-forms-item>
      <uni-forms-item label="客户开户行" label-width="90px" name="bank_name">
        <uni-easyinput v-model="customerFormData.bank_name" placeholder="请输入客户开户行" />
      </uni-forms-item>
      <uni-forms-item label="开户行账号" label-width="90px" name="bank_account">
        <uni-easyinput v-model="customerFormData.bank_account" placeholder="请输入开户行账号" />
      </uni-forms-item>
      <uni-forms-item label="开户行地址" label-width="90px" name="invoice_addr">
        <uni-easyinput v-model="customerFormData.invoice_addr" placeholder="请输入开户行地址" />
      </uni-forms-item>
      <uni-forms-item label="开户行电话" label-width="90px" name="invoice_phone">
        <uni-easyinput v-model="customerFormData.invoice_phone" placeholder="请输入开户行电话" />
      </uni-forms-item>
      <uni-forms-item label="备注信息" label-width="90px" name="memo">
        <uni-easyinput type="textarea" v-model="customerFormData.memo" placeholder="请输入客户备注信息" />
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;display: flex;">
      <custom-button width="100%" type="filled" color="#dd524d" @click="restForm()"
        style="margin-right: 5px;flex:1">重置</custom-button>
      <custom-button width="100%" type="filled" color="#007aff" style="flex:1;"
        @click="handlerAddCustomer()">提交</custom-button>
    </view>
    <next-tree :ifSearch="true" :showAuxiliaryLine="true" :border="true" labelKey="name" ref="regionTreeRef"
      :checkStrictly="true" :selectParent="true" funcMode="radio" :treeData="regionTreeData"
      @confirm="confirmRegion"></next-tree>
    <next-tree :ifSearch="true" :showAuxiliaryLine="false" :border="true" labelKey="name" ref="accountTreeRef"
      :checkStrictly="true" :selectParent="true" funcMode="radio" :treeData="accountList"
      @confirm="confirmAccount"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getCustomerLevelList, getIndustryTypeList } from '@/api/base/base';
import { getStaffList } from '@/api/biz/staff';
import SelectItemModal from '@/components/selected-list-item/index.vue'
import nextTree from '@/components/next-tree/next-tree.vue'
import { DomainTree } from '@/types/domain';
import { AddCustomerReqParams } from '@/types/customer';
import { addCustomer } from '@/api/biz/customer';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { getRegionTree } from '@/api/base/region';
const showCheckboxDrawer = ref(false)
const accountList = ref<{ id: string, name: string }[]>([])
const customerLevelList = ref<{ value: string, text: string }[]>([])
const regionTreeData = ref<DomainTree[]>([]) // 区域树
const customerFormRef = ref()
const regionTreeRef = ref()
const accountTreeRef = ref()
const industryList = ref<{ value: string; text: string }[]>([])
const { emitter } = useEmitt()

const rules = {
  // 对name字段进行必填验证
  name: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '名称不能为空',
      }
    ]
  },
  industry_id: {
    rules: [
      {
        required: true,
        errorMessage: '行业信息不能为空',
      }
    ]
  },
  region_id: {
    rules: [
      {
        required: true,
        errorMessage: '所属区域不能为空',
      }
    ]
  },
  level_id: {
    rules: [
      {
        required: true,
        errorMessage: '客户级别不能为空',
      }
    ]
  }
}
const customerFormData = ref<{
  name?: string
  industry_id?: string
  industry_name?: string
  region_name?: string
  region_id?: number
  level_id?: string
  link_man?: string
  link_phone?: string
  address?: string
  invoice_title?: string
  tax_no?: string
  bank_name?: string
  bank_account?: string
  invoice_addr?: string
  invoice_phone?: string
  bizman_id?: string
  bizman_name?: string
  memo?: string
}>({

})
const range = [
  { value: 0, text: "篮球" },
  { value: 1, text: "足球" },
  { value: 2, text: "游泳" },
]

const showCheckBoxDrawer = async () => {
  // await get
  checkedTreeData(unref(accountList), customerFormData.value.bizman_id)
  unref(accountTreeRef).showTree = true
  // showCheckboxDrawer.value = true
}
const closeCheckBoxDrawer = (id?: string) => {
  customerFormData.value.bizman_id = id;
  customerFormData.value.bizman_name = accountList.value.find(item => item.id === id)?.name
  showCheckboxDrawer.value = false
}

function checkedTreeData(treeData: any, selectIds?: number | string) {
  treeData.map((item: any) => {
    if (selectIds === item.id) {
      item.checked = true
    } else {
      item.checked = false
    }
    if (item.children && item.children.length) {
      checkedTreeData(item.children, selectIds)
    }
  })
}

const showRegionModal = async () => {
  checkedTreeData(unref(regionTreeData), customerFormData.value.region_id)
  unref(regionTreeRef).showTree = true
}

/**
 * 递归获取ng-tree需要的结构体
 * @param domains 接口返回的树状数组
 */
const getNodesTree = (domains: DomainTree): DomainTree => {
  domains.key = domains.id.toString()
  if (domains.children && domains.children.length > 0) {
    domains.children.map(res => getNodesTree(res))
  }
  return domains
}

/**
 * 获取区域树
 */
const getTree = async () => {
  const { tree } = await getRegionTree()
  regionTreeData.value = tree
}

/**
* 获取用户列表
*/
const getAccountList = async () => {
  try {
    const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
    accountList.value = list
  } catch (e) {
    console.error(e)
  }
}

const getIndustryType = async () => {
  const { list } = await getIndustryTypeList()
  industryList.value = list.map(item => {
    return {
      value: item.id,
      text: item.name
    }
  })

}

const getLevels = async () => {
  const { list } = await getCustomerLevelList()
  customerLevelList.value = list.map(item => {
    return {
      value: item.id,
      text: item.name
    }
  })
}

function confirmRegion(list: DomainTree[]) {
  if (list.length > 0) {
    customerFormData.value.region_id = list[0].id
    customerFormData.value.region_name = list[0].name
  }else{
    customerFormData.value.region_id = undefined
    customerFormData.value.region_name = undefined
  }
}

function confirmAccount(list: { id: string, name: string }[]) {
  if (list.length > 0) {
    customerFormData.value.bizman_id = list[0].id
    customerFormData.value.bizman_name = list[0].name
  }else{
    customerFormData.value.bizman_id = undefined
    customerFormData.value.bizman_name = undefined
  }
}


const handlerAddCustomer = async () => {
  const isValid = await customerFormRef.value?.validate()
  if (!isValid) {
    return
  }
  const { name, region_id, address, industry_id, level_id, link_man, link_phone, bank_account, bank_name, bizman_id, invoice_addr, invoice_phone, invoice_title, memo, tax_no } = unref(customerFormData)
  const params: AddCustomerReqParams = {
    name: name!,
    region_id: region_id!,
    industry_id: industry_id!,
    level_id: level_id!,
    link_man,
    link_phone,
    bank_account,
    bank_name,
    bizman_id,
    invoice_addr,
    invoice_phone,
    invoice_title,
    tax_no,
    address,
    memo
  }
  await addCustomer(params)
  emitter.emit('get_customer_list')
  uni.showModal({
    title: '添加成功',
    content: `是否返回客户管理页面`,
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if(confirm){
        return uni.navigateBack()
      }
    }
  })
  // const {}
}


const restForm = async()=>{
  customerFormData.value = {}
  customerFormRef.value?.clearValidate()
}


onMounted(() => {
  getAccountList()
  getIndustryType()
  getLevels()
  getTree()
})

</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'apply-shared', //解除样式隔离
  }

}
</script>
<style scoped>
.example {
  padding: 15px;
  background-color: #fff;
}

:deep(.is-disabled) {
  color: #333;

}

.custom-select-class {
  border-color: #e5e5e5;
  background-color: transparent;
  display: flex;
  box-sizing: border-box;
  flex-direction: row;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.custom-select-content {
  width: auto;
  position: relative;
  overflow: hidden;
  flex: 1;
  line-height: 1;
  font-size: 14px;
  line-height: 35px;
  padding-left: 10px;
  height: 35px;
}
</style>