<template>

  <view class="example">
    <!-- 展示不同的排列方式 -->
    <uni-forms ref="contractFormRef" :modelValue="contractFormData" :rules="rules" validateTrigger="submit"
      label-position="top">
      <uni-forms-item label="合同名称" required label-width="90px" name="name">
        <uni-easyinput v-model="contractFormData.name" placeholder="请输入合同名称" />
      </uni-forms-item>
      <uni-forms-item label="合同客户" required label-width="90px" name="customer_id">
        <view class="custom-select-class" @click="showTreeSelectModal(customerList, 0, [contractFormData.customer_id])">
          <view class="custom-select-content">
            <text v-if="contractFormData.customer_id">{{ contractFormData.customer_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="prj_id">
        <view class="custom-select-class" @click="showTreeSelectModal(projectList, 1, [contractFormData.prj_id])">
          <view class="custom-select-content">
            <text v-if="contractFormData.prj_id">{{ contractFormData.prj_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="合同金额（万元）" required label-width="130px" name="amount">
        <view class="uni-easyinput">
          <view class="uni-easyinput__content is-input-border" :style="{
            borderColor: is_foucs ? '#2979ff' : '',
            background: is_foucs ? '#fff' : ''
          }">
            <input class="uni-easyinput__content-input" v-model="contractFormData.amount"
              placeholder-class="uni-easyinput__placeholder-class" :focus="is_foucs" type="digit" placeholder="输入合同金额"
              @focus="is_foucs = true" @blur="handlerAmountBlur()">
          </view>
        </view>
        <!-- <uni-datetime-picker type="date" v-model="contractFormData." /> -->
      </uni-forms-item>
      <uni-forms-item label="合同签订人" required label-width="90px" name="handler_id">
        <view class="custom-select-class" @click="showTreeSelectModal(accountList, 2, [contractFormData.handler_id])">
          <view class="custom-select-content">
            <text v-if="contractFormData.handler_id">{{ contractFormData.handler_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="签订日期" required label-width="90px" name="signed_at">
        <uni-datetime-picker type="date" v-model="contractFormData.signed_at" />
      </uni-forms-item>
      <uni-forms-item label="合同起始日" required label-width="90px" name="begin_at">
        <uni-datetime-picker type="date" v-model="contractFormData.begin_at" />
      </uni-forms-item>
      <uni-forms-item label="合同结束日" label-width="90px" name="end_at">
        <uni-datetime-picker type="date" v-model="contractFormData.end_at" />
      </uni-forms-item>
      <uni-forms-item label="合同摘要" label-width="90px" name="intro">
        <uni-easyinput type="textarea" v-model="contractFormData.comment" placeholder="请输入合同摘要" />
      </uni-forms-item>
      <uni-section title="收款约定" type="line">
        <template v-slot:right>
          <view style="color: #007aff;display: flex;align-items: center;" @click="redirectAddContractPaymentPage()">
            <uni-icons :size="14" color="#007aff" type="plusempty"></uni-icons>
            <text>添加</text>
          </view>
        </template>
      </uni-section>
      <uni-swipe-action ref="swiper_action">
        <uni-swipe-action-item :right-options="options" class="swipe-action-item" :threshold="20"
          v-for="(item, index) in contractFormData.payments" :key="index"
          @click="(e: any) => handlerSwipeAction(e, item, index)">
          <uni-card margin="5px" padding="0px" :title="item.condition" :extra="`${item.percent}%`" spacing="5px"
            :sub-title="item.memo" thumbnail="./../../../../../static/images/payment.png">
            <view>
              <view class="card-actions">
                <text class="subtitle font-size-base">收款金额：<text class="font-size-base" style="color: #007aff;">{{
                  Math.round(
                    (contractFormData.amount || 0) *
                    item.percent *
                    100
                  ) / 10000
                    }} 万元</text></text>
                <text class="subtitle font-size-base">收款日期：<text class="paragraph font-size-sm">{{ item.expect_pay_date
                    }}</text></text>

              </view>
            </view>
          </uni-card>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </uni-forms>
    <view style="margin: 10px 0;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="handlerAddContract()">提交</custom-button>
    </view>
    <next-tree :ifSearch="true" :border="true" labelKey="name" ref="treeSelectRef" :funcMode="'radio'"
      :treeData="treeSelectData" @confirm="confirmTreeSelect" @cancel="cancelTreeSelect"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getPrjTypeList } from '@/api/base/base';
import { getStaffList } from '@/api/biz/staff';
import nextTree from '@/components/next-tree/next-tree.vue'
import { DomainTree } from '@/types/domain';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { getProjectList } from '@/api/project-center/info';
import { getCustomerList } from '@/api/biz/customer';
import { AddContractReqParams, Payment } from '@/types/contract';
import { addContract } from '@/api/project-center/contract';

const swiper_action = ref()
const treeDataType = ref<number>(0)
const accountList = ref<{ id: string, name: string }[]>([])
const customerList = ref<{ id: string, name: string }[]>([])
const projectList = ref<{ id: string, name: string }[]>([])
const treeSelectData = ref<DomainTree[]>([]) // 区域树
const contractFormRef = ref()
const is_foucs = ref(false)
const treeSelectRef = ref()
const { emitter } = useEmitt()


const options = [
  {
    text: '修改',
    style: {
      backgroundColor: '#4cd964',
      margin: "5px 0"
    }
  },
  {
    text: '删除',
    style: {
      backgroundColor: '#dd524d',
      margin: "5px 0"
    }
  }
]

const rules = {
  // 对name字段进行必填验证
  name: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '名称不能为空',
      }
    ]
  },
  customer_id: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '合同客户不能为空',
      }
    ]
  },
  amount: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '合同金额不能为空',
      }
    ]
  },
  handler_id: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '合同签订人不能为空',
      }
    ]
  },
  signed_at: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '签订日期不能为空',
      }
    ]
  },
  begin_at: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '合同起始日不能为空',
      }
    ]
  }
}

const contractFormData = ref<{
  name?: string
  customer_id?: string // 
  customer_name?: string // 
  prj_id?: string // 
  prj_name?: string // 
  handler_id?: string // 
  handler_name?: string //
  amount?: number // 
  signed_at?: string
  begin_at?: string
  end_at?: string
  comment?: string
  payments?: Payment[]
}>({})



function checkedTreeData(treeData: any, selectIds?: any) {
  treeData.map((item: any) => {
    if (selectIds.indexOf(item.id) !== -1) {
      item.checked = true
    } else {
      item.checked = false
    }
    if (item.children && item.children.length) {
      checkedTreeData(item.children, selectIds)
    }
  })
}

const showTreeSelectModal = async (treeData: any, type: number, selectId?: any) => {
  treeDataType.value = type;
  treeSelectData.value = treeData;
  checkedTreeData(treeSelectData.value, selectId)
  unref(treeSelectRef).showTree = true
}

// 只保留到6位
const handlerAmountBlur = () => {
  is_foucs.value = false
  if (![undefined, null, '', 0].includes(contractFormData.value.amount)) {
    contractFormData.value.amount = Math.round(Number(contractFormData.value.amount) * 10000) / 10000
  }
}

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




// 获取客户列表
const getCustomers = async () => {
  try {
    const params = {
      page_no: 1,
      page_size: 9999,
    }
    const { list } = await getCustomerList(params)
    customerList.value = list
  } catch (e) {
    console.error(e)
  }
}

const getProjects = async (name?: string) => {
  try {
    const { list } = await getProjectList({ page_no: 1, page_size: 9999 })
    projectList.value = list
  } catch (e) {
    console.error(e)
  }
}



function confirmTreeSelect(list: any) {
  switch (treeDataType.value) {
    case 0:
      if (list.length > 0) {
        contractFormData.value.customer_id = list[0].id
        contractFormData.value.customer_name = list[0].name
      } else {
        contractFormData.value.customer_id = undefined
        contractFormData.value.customer_name = undefined
      }
      break;
    case 1:
      if (list.length > 0) {
        contractFormData.value.prj_id = list[0].id
        contractFormData.value.prj_name = list[0].name
      } else {
        contractFormData.value.prj_id = undefined
        contractFormData.value.prj_name = undefined
      }
      break;
    case 2:
      if (list.length > 0) {
        contractFormData.value.handler_id = list[0].id
        contractFormData.value.handler_name = list[0].name
      } else {
        contractFormData.value.handler_id = undefined
        contractFormData.value.handler_name = undefined
      }
      break;
    default:
      break;
  }
  treeSelectData.value = [];
}


const cancelTreeSelect = () => {
  treeSelectData.value = []
  // checkedTreeData(unref(tr), []) 
}

function calculateRemainingAmount(payments: Payment[], excludeIndex?: number): number {
  const totalPaidPercentage = payments.reduce((total, payment, index) => {
    // 如果当前的下标等于要排除的下标，则不累加其percent值
    if (index === excludeIndex) {
      return total;
    }
    return total + payment.percent;
  }, 0);
  const percent = 100 - totalPaidPercentage
  return Math.round(percent * 100) / 100
}

//跳转添加收款约定页面
const redirectAddContractPaymentPage = () => {
  if ([undefined, null, '', 0].includes(contractFormData.value.amount)) {
    uni.showToast({
      icon: 'error',
      title: '合同金额不足'
    })
    return
  }
  const amount = Number(contractFormData.value.amount)
  const remainingPercentage = calculateRemainingAmount(contractFormData.value.payments || [])
  if (remainingPercentage === 0) {
    uni.showToast({
      icon: 'none',
      title: '收款比例已用完'
    })
    return
  }
  uni.navigateTo({
    url: `/pages/profile/contract/add-payment?total_amount=${amount}&remaining_percentage=${remainingPercentage}`
  })
}

// swipe action操作。修改约定或删除收款约定
const handlerSwipeAction = (e: { index: number }, payment: Payment, pIndex: number) => {
  swiper_action.value?.closeAll()
  const { index } = e;
  const isEdit = index === 0;
  const isRemove = index === 1;
  if (isRemove) {
    contractFormData.value.payments?.splice(pIndex, 1)
    return
  }
  if (isEdit) {  // 跳转修改收款约定页面
    const amount = Number(contractFormData.value.amount)
    const remainingPercentage = calculateRemainingAmount(contractFormData.value.payments || [], pIndex)
    uni.navigateTo({
      url: `/pages/profile/contract/edit-payment?total_amount=${amount}&remaining_percentage=${remainingPercentage}`,
      success: () => {
        emitter.emit('editor_payment_item', {
          index: pIndex,
          payment: payment
        })
      }
    })
  }
}

const handlerAddContract = async () => {
  const isValid = await contractFormRef.value?.validate()
  if (!isValid) {
    return
  }
  const { name, customer_id, prj_id, handler_id, signed_at, begin_at, end_at, comment, amount, payments } = contractFormData.value
  const params: AddContractReqParams = {
    name: name!,
    customer_id: customer_id!,
    prj_id,
    handler_id: handler_id!,
    signed_at: signed_at!,
    begin_at: begin_at!,
    end_at,
    comment,
    amount: Number(amount)!,
    payments: payments
  }

  await addContract(params)
  emitter.emit('get_contract_list')
  uni.showModal({
    title: '添加成功',
    content: `是否返回合同管理页面`,
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        return uni.navigateBack()
      }
    }
  })
}


const restForm = async () => {
  contractFormData.value = {}
  contractFormRef.value?.clearValidate()
}

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'add_payment',
  callback: (payment: Payment) => {
    const payments = contractFormData.value.payments || []
    payments.push(payment)
    contractFormData.value.payments = payments
  }
})

useEmitt({
  name: 'modify_payment',
  callback: (e: { index: number, payment: Payment }) => {
    const { index, payment } = e;
    const payments = contractFormData.value.payments || []
    payments.splice(index, 1, payment)
  }
})



onMounted(() => {
  getAccounts()
  getProjects()
  getCustomers()
})

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

}
</script>
<style scoped lang="scss">
.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;

}

.tag-container {
  &__item {
    padding: 0 6px 0 0;
  }
}

.uni-easyinput {
  /* #ifndef APP-NVUE */
  width: 100%;
  /* #endif */
  flex: 1;
  position: relative;
  text-align: left;
  color: #333;
  font-size: 14px;
}

.uni-easyinput__content {
  flex: 1;
  /* #ifndef APP-NVUE */
  width: 100%;
  display: flex;
  box-sizing: border-box;
  // min-height: 36px;
  /* #endif */
  flex-direction: row;
  align-items: center;
  // 处理border动画刚开始显示黑色的问题
  border-color: #fff;
  transition-property: border-color;
  transition-duration: 0.3s;
}

.is-input-border {
  display: flex;
  box-sizing: border-box;
  flex-direction: row;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.uni-easyinput__content-input {
  /* #ifndef APP-NVUE */
  width: auto;
  /* #endif */
  position: relative;
  overflow: hidden;
  flex: 1;
  line-height: 1;
  font-size: 14px;
  padding-left: 10px;
  height: 35px;
  // min-height: 36px;

  /*ifdef H5*/
  & ::-ms-reveal {
    display: none;
  }

  & ::-ms-clear {
    display: none;
  }

  & ::-o-clear {
    display: none;
  }

  /*endif*/
}

.content-clear-icon {
  padding: 0 5px;
}

:deep(.uni-easyinput__placeholder-class) {
  color: #999;
  font-size: 12px;
  // font-weight: 200;
}

:deep(.uni-section .uni-section-header) {
  padding: 12px 0
}

:deep(.uni-swipe_button-group) {
  top: 5px;
  bottom: 5px;
}

.uni-mt-5 {
  margin-top: 5px;
}

.border-top {
  border-top: 1px #eee solid;
}

.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 25px;
  line-height: 25px;
  font-size: $uni-font-size-sm;
  padding: 5px 10px 0 10px;
}

.progress-actions {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  height: 25px;
  line-height: 25px;
  font-size: $uni-font-size-sm;
  padding: 5px 10px 0 10px;
}

.font-size-sm {
  font-size: $uni-font-size-sm;
}

.font-size-base {
  font-size: 26rpx;
}

.paragraph {
  color: #b2a9a6;
  font-weight: 600;
}

.subtitle {
  color: #b2a9a6;
}

:deep(.uni-ellipsis) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

:deep(.uni-card__header-extra-text) {
  font-size: 16px !important;
  color: #3a3a3a !important;
  font-weight: bold !important;
}
</style>