<template>
  <z-paging ref="paging" v-model="contractList" @query="queryList" :default-page-size="detaultPageSize" empty-view-text="暂无合同数据"
    :safe-area-inset-bottom="true">
    <template #top>
      <custom-dropdown ref="dropdownRef" :dropdownMenu="dropdownMenuList" themeColor="#007aff"
        style="width:100%;border-top: 1px solid #edf0f9;" textColor="#333333" :duration="300" @confirm="handleConfirm"
        @close="handleClose" bgColor="#f8f8f8" @open="handleOpen">
        <template #slot1="{ item, index }">
          <view style="width: 100%;height: 300px;">
            <next-tree ref="regionTreeRef" :ifSearch="true" :showDropdownFooter="true" :border="true" labelKey="name"
              :showBottomBar="true" funcMode="radio" :treeData="prjList" uiMode="page" @confirm="confirmProject">
            </next-tree>
          </view>
        </template>
        <template #slot2="{ item, index }">
          <view style="margin: 40rpx 40rpx 0">
            <uni-easyinput prefixIcon="search" v-model="customer_name" placeholder="按客户名称模糊查询" @clear="resetCustomer">
            </uni-easyinput>
            <PartDropdownFooter @reset="resetCustomer" @confirm="confirmCustomer" />
          </view>
        </template>
      </custom-dropdown>
    </template>
    <List :contract-list="contractList" />
    <template #bottom>
      <view style="padding: 0 10px;position: relative;bottom: 1px;">
        <custom-button width="100%"  color="#007aff" :radius="['5px']" ripple
          @click="redirectAddContractPage()">录入合同</custom-button>
      </view>
    </template>
  </z-paging>
</template>

<script lang="ts" setup>
import List from './List.vue'
import { useEmitt } from '@/logics/mitt/useEmitt';
import customDropdown from '@/components/cu-dropdown/index.vue'
import PartDropdownFooter from '@/components/cu-dropdown/components/part-dropdown-footer.vue'
import nextTree from '@/components/next-tree/next-tree.vue'
import { getProjectList } from '@/api/project-center/info';
import { getContractList } from '@/api/project-center/contract';
import { getStaffList } from '@/api/biz/staff';
import { Contract } from '@/types/contract';

const detaultPageSize = 10;
const paging = ref()
const customer_name = ref()
const contractList = ref<Contract[]>([])
const dropdownRef = ref()
const prjList = ref<{ id: string, name: string }[]>([])

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
  name?: string
  prj_id?: string
  date?: string[]
  customer_name?: string
  handler_id?: number
}>({
  name: undefined,
  prj_id: undefined,
  customer_name: undefined,
  handler_id: undefined,
  date: undefined
})

const dropdownMenuList = ref([
  {
    title: '合同名称',
    type: 'search',
    prop: 'name',
    placeholder: '按合同名称搜索'
  },
  {
    title: '所属项目',
    type: 'slot1',
    prop: 'prj_id',
    showArrow: true,
    showIcon: true,
  },
  {
    title: '签订客户',
    type: 'slot2',
    prop: 'customer_name',
    showArrow: true,
    showIcon: true,
  },
  {
    title: '签订人员',
    type: 'cell',
    prop: 'handler_id',
    showArrow: true,
    showIcon: true,
    field: {
      label: 'name',
      value: 'id'
    },
    options: []
  },
  {

    title: '时间范围',
    showAll: true,
    showIcon: true,
    type: 'daterange',
    prop: 'date'
  },
])

/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
  const {
    name,
    prj_id,
    handler_id,
    customer_name,
    date
  } = filterForm
  const begin_from = date ? date[0] : date
  const end_to = date ? date[1] : date
  return {
    name,
    prj_id,
    handler_id,
    customer_name,
    begin_from,
    end_to
  }
}

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = async (pageNo: number, pageSize: number) => {
  try {
    const { name, prj_id, handler_id, begin_from, end_to, customer_name } = getFilterForm()
    const { list } = await getContractList({ page_no: pageNo, page_size: pageSize, name, prj_id, customer_name, begin_from, end_to, handler_id })
    paging.value?.complete(list);
  } catch (e) {
    paging.value.complete(false);
  }
}

const resetCustomer = () => {
  customer_name.value = undefined
}

const confirmCustomer = () => {
  if (![undefined, null, ''].includes(customer_name.value)) {
    dropdownRef.value?.updateMenu('customer_name', customer_name.value, 'value')
    dropdownRef.value?.updateMenu('customer_name', true, 'isActived')
  } else {
    dropdownRef.value?.updateMenu('customer_name', undefined, 'value')
    dropdownRef.value?.updateMenu('customer_name', false, 'isActived')
  }
  dropdownRef.value?.closeMenuPopup()
  handleConfirm(2)
}


const confirmProject = (v: { id: string }[]) => {
  if (v.length > 0) {
    dropdownRef.value?.updateMenu('prj_id', v[0].id, 'value')
    dropdownRef.value?.updateMenu('prj_id', true, 'isActived')
  } else {
    dropdownRef.value?.updateMenu('prj_id', undefined, 'value')
    dropdownRef.value?.updateMenu('prj_id', false, 'isActived')
  }
  dropdownRef.value?.closeMenuPopup()
  handleConfirm(1)
}

// 跳转录入合同页面
const redirectAddContractPage = () => {
  uni.navigateTo({ url: `/pages/profile/contract/add-contract` })
}

async function handleOpen(index: number) {
  if (index === 2) {
    customer_name.value = filterForm.customer_name
  }

}

function handleClose(index: number) {
  console.log('handleClose ==>', index)

}

function handleConfirm(v: any) {
  const dropdownValues = dropdownRef.value?.getMenuValue()
  filterForm.prj_id = dropdownValues.prj_id
  filterForm.handler_id = dropdownValues.handler_id
  filterForm.customer_name = dropdownValues.customer_name
  filterForm.name = dropdownValues.name
  filterForm.date = dropdownValues.date ? [dropdownValues.date.start, dropdownValues.date.end] : dropdownValues.date
  paging.value?.reload()
}



// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get_contract_list',
  callback: () => {
    console.log('刷新')
    paging.value?.reload()
  }
})


/**
 * 获取项目列表
 */
const getProjects = async () => {
  try {
    const { list } = await getProjectList({ page_no: 1, page_size: 9999 })
    prjList.value = list
  } catch (e) {
    console.error(e)
  }
}

/**
 * 获取项目列表
 */
const getAccounts = async () => {
  try {
    const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
    nextTick(() => {
      dropdownRef.value?.updateMenu('handler_id', [{ name: '不限', id: '-9999' }, ...list], 'options')
    })
  } catch (e) {
    console.error(e)
  }
}

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

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

}
</script>
<style scoped lang="scss">
.c-nav-bar {
  &__content {
    color: red;
  }
}

.is-hover {
  color: rgba(255, 255, 255, 0.6);
  background-color: #179b16;
  border-color: #179b16;
}

.city {
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  margin-left: 4px;
}

.box-bg {
  background-color: #F5F5F5;
}


.input-view {
  /* #ifndef APP-PLUS-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  flex: 1;
  flex-wrap: nowrap;
  margin: 7px 3px 7px 0px;
  line-height: 30px;
}

.input-uni-icon {
  line-height: 30px;
}

.nav-bar-input {
  height: 30px;
  line-height: 30px;
  /* #ifdef APP-PLUS-NVUE */
  /* #endif */
  padding: 0 5px;
  font-size: 12px;
  background-color: #f8f8f8;
}

:deep(.uni-searchbar__box-icon-clear) {
  padding-top: 5px;
}

.uni-navbar {
  &__header {
    padding: 0 !important
  }
}

:deep(.uni-searchbar) {
  padding: 0;
  width: 100%;
}

:deep(.uni-searchbar__box) {
  height: 30px !important;
}

:deep(.uni-navbar__header-container) {
  padding: 0px !important;
}


:deep(.uni-searchbar__cancel) {
  height: 30px;
  line-height: 30px;
}
</style>