import { Button, Input, Textarea, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Form from './components/form'
import {
  MpCashManagementOrderAccount, MpCashManagementOrderPost,
  MpShouldCollectOrderPurchaser,
} from '@/api/newCollection'
import { alert } from '@/common/common'
import smallToBig from '@/common/money'
import IconFont from '@/components/iconfont/iconfont'

const AddCollection = () => {
  // 获取选择的客户
  const pages = Taro.getCurrentPages()
  const currPage = pages[pages.length - 1] // 获取当前页面

  const [Query, setQuery] = useState<any>({})

  // 获取图片列表
  const picUrl = useRef([])
  const getImageList = useCallback((list) => {
    picUrl.current = list
    setQuery(val => ({ ...val, picList: list }))
  }, [])

  // 获取首个银行账号
  const { fetchData: clitentFetch } = MpCashManagementOrderAccount()
  const getCuss = async() => {
    const res = await clitentFetch({ page: 1, size: 10 })
    if (res.data) {
      setQuery(val => ({ ...val, bankId: res.data.list[0].receiving_account_id, bankName: res.data.list[0].company_account }))
    }
  }

  const { fetchData: scanFetch } = MpShouldCollectOrderPurchaser()
  // 扫描
  const handScan = (e) => {
    e.stopPropagation()
    Taro.scanCode({
      async success(res) {
        const restult = await scanFetch({ order_no: res.result })
        setQuery(val => ({ ...val, purchaser_id: restult.data.purchaser_id, clientName: restult.data.purchaser_name }))
      },
      fail(res) {
        console.log(res)
      },
    })
  }

  // 选择内容跳转
  const navTo = (val) => {
    if (val == 1) {
      Taro.navigateTo({
        url: `/pages/customerPage/index?clientId=${Query.purchaser_id}`,
      })
    }
    else {
      if (typeof (Query.purchaser_id) == 'undefined') {
        return alert.error('请先选择客户')
      }
      else {
        Taro.navigateTo({
          url: `/pages/accountPage/index?bankId?=${Query?.bankId}`,
        })
      }
    }
  }
  useDidShow(() => {
    setQuery(e => ({
      ...e,
      purchaser_id: currPage.data?.clientId ? currPage.data?.clientId : Query.purchaser_id,
      clientName: currPage.data?.clientName ? currPage.data?.clientName : Query.clientName,
      bankId: currPage.data?.bankId ? currPage.data?.bankId : Query.bankId,
      bankName: currPage.data?.bankName ? currPage.data?.bankName : Query.bankName,
    }))
  })
  useEffect(() => {
    getCuss()
  }, [])
  // 判断是否可以提交
  const isDisabled = useMemo(() => {
    if (Query.clientName == ''
            || Query.money == ''
            || Query.picList?.length == 0
    ) {
      return true
    }
    else {
      return false
    }
  }, [Query])

  // 收款金额回调
  const getInput = (e) => {
    setQuery({ ...Query, money: e })
  }

  useEffect(() => {
    setQuery(Query)
  }, [Query])

  // useEffect(() => {
  //     if (currPage.data?.clientId && (currPage.data?.clientId != Query.purchaser_id)) {
  //         setQuery({ ...Query, bankId: '', bankName: '' })
  //     }
  // }, [Query])

  // 备注信息
  const [TextareaValue, setTextareaValue] = useState('')
  const getDesc = (e) => {
    setQuery({ ...Query, nums: e.length })
    setTextareaValue(e)
  }

  // 取消返回
  const handCancl = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }

  // 确认新建
  const { fetchData: sureFetch } = MpCashManagementOrderPost()
  const handSure = () => {
    const query = {
      payment_credential_url: picUrl.current,
      purchaser_id: Query.purchaser_id,
      receipt_amount: Number(Query.money) * 100,
      receiving_account_id: Query.bankId,
      remark: TextareaValue,
    }
    Taro.showModal({
      content: '确认提交吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          const res = await sureFetch(query)
          if (res?.msg === 'success') {
            Taro.showToast({
              title: '成功',
            })
            Taro.hideLoading()
            handCancl()
          }
          else {
            Taro.hideLoading()
            Taro.showToast({
              title: res?.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }

  const [IsOpen, setIsOpen] = useState(false)
  const handOpen = () => {
    if (IsOpen) {
      setIsOpen(false)
    }
    else {
      setIsOpen(true)
    }
  }

  const openFont = useMemo(() => {
    if (IsOpen) {
      return '收起'
    }
    else {
      return '展开'
    }
  }, [IsOpen])
  return (
    <>
      <View className={classnames(IsOpen === false ? styles.addBox : styles.activeBox)}>
        <Form
          isOpen
          title="客户名称"
          require
          isInput
          disabled
          placeholderFont="请选择客户信息"
          inputValue={Query.clientName}
          showMore
          showScan
          styleNone
          showPic={false}
          getScan={e => handScan(e)}
          navTo={() => navTo(1)}
          showSizeFont={false}
        ></Form>
        <Form
          isOpen
          title="收款金额"
          require
          isInput
          disabled={false}
          placeholderFont="请输入金额"
          inputType="digit"
          showMore={false}
          inputValue={Query.money}
          showScan={false}
          styleNone
          showPic={false}
          getInput={e => getInput(e)}
          showSizeFont
          bigMoney={smallToBig(typeof (Query.money) == 'undefined' ? 0 : Query.money)}
        ></Form>
        <Form
          isOpen
          styleNone={false}
          title="收款凭证"
          require
          isInput={false}
          showMore={false}
          showScan={false}
          showPic
          getImageList={list => getImageList(list)}
          showSizeFont={false}
        ></Form>
        <Form
          isOpen={IsOpen}
          title="收款账户"
          require={false}
          isInput
          disabled
          placeholderFont="请选择银行账号"
          inputValue={Query.bankName}
          showMore
          showScan={false}
          styleNone
          showPic={false}
          navTo={() => navTo(2)}
          showSizeFont={false}
        ></Form>
        {
          IsOpen && <View className={styles.textAreaBox}>
            <View className={styles.textAreaLeft}>备注信息</View>
            <View className={styles.textAreaRight}>
              <Textarea
                style={{ width: '70%' }}
                onInput={e => getDesc(e.detail.value)}
                value={TextareaValue}
                placeholderStyle="font-size: 28rpx;font-weight: 400;"
                maxlength={64}
                placeholder="请填写备注信息"
              ></Textarea>
              <View className={styles.numsTotal}>{`${typeof (Query.nums) == 'undefined' ? 0 : Query.nums}/64`}</View>
            </View>
          </View>
        }
        <View className={styles.openBox} onClick={() => handOpen()}>
          <View className={styles.openFont}>{openFont}</View>
          {
            !IsOpen && <IconFont name="icon-zhankai" size={30} color="#337FFF" ></IconFont>
          }
          {
            IsOpen && <IconFont name="icon-shouqi" size={30} color="#337FFF" ></IconFont>
          }
        </View>
      </View >
      <View className={styles.safeBox}> </View>
      <View className={styles.bottomBox}>
        <Button className={styles.resetBox} onClick={() => { handCancl() }}> 取消</Button >
        <Button className={classnames(isDisabled ? styles.button : styles.activeButton)} disabled={isDisabled} onClick={() => handSure()}> 提交</Button >
      </View>
    </>
  )
}

export default AddCollection
