<template>
  <div class="register">
    <van-nav-bar
      title="加工建单" left-arrow fixed placeholder @click-left="goBack" @click-right="onConfirm()">
      <template #left>
        <van-icon name="arrow-left" size="25" />
        <div style="color: #fff">返回</div>
      </template>
      <template #right>
        <div style="color: #fff">提交</div>
      </template>
    </van-nav-bar>
    <van-field v-model="date" type="text" label="登记日期" placeholder="请选择日期"
               readonly is-link input-align="right" @click="dateTrueFalseBy=true" required
    />
    <van-field v-model="ownerCode" type="text" label="登记货主" placeholder="请选择货主" readonly
               is-link @click="ownerRef.show(1)" input-align="right" required
    />
    <van-field v-model="code" type="textarea" label="单据信息" placeholder="请填写快递单号/收货任务号，多个用逗号/空格/换行符进行分割"
               show-word-limit maxlength="500" rows="2" autosize required
    />
    <van-field v-model="note" type="textarea" label="&nbsp;&nbsp;备注信息" placeholder="请输入备注信息"
               show-word-limit  maxlength="500" rows="1" autosize
    />
    <div class="register-content">
      <div class="add-type">
        <van-button type="primary" round size="small" @click="addType">添加类型</van-button>
      </div>
      <div class="type-box">
        <div class="type-title">类型表一览</div>
        <div class="type-list">
          <div class="type-item">
            <div class="type-item-item">类型</div>
            <div class="type-item-operate">数量</div>
            <div class="type-item-operate">操作</div>
          </div>
          <div  class="type-item" v-for="(item,index) in typeList" v-if="typeList.length>0">
            <div  class="type-item-item">{{getOperate(item.operate)}}</div>
            <div class="type-item-operate">{{item.expectAmount}}</div>
            <div class="type-item-delete" @click="del(item,index)" >删除</div>
          </div>
          <div v-else>
            <van-empty :image="<string>nodataUrl" image-size="140" >
              <van-button round type="primary" class="bottom-button" size="small" @click="addType">添加</van-button>
            </van-empty>
          </div>
        </div>
      </div>
    </div>
    <owner ref="ownerRef" @onOwner="onOwner" />
    <van-calendar first-day-of-week="1" v-model:show="dateTrueFalseBy" @confirm="dateConfirm" />
    <add-register-type ref="addRegisterTypeRef"
                       :processingTypeList="processingTypeList"
                       @setProcessingType="setProcessingType"  />
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { getHeader, goBack, scanError, scanSuccess } from '@/utils/android'
import { showConfirmDialog, showNotify, showToast } from 'vant'
import { useStore } from '@/store/modules/user'
import { closeLoading, showLoading } from '@/utils/loading'
import Owner from '@/components/Owner.vue'
import { formatDate } from '@/utils/date'
import { useRouter } from 'vue-router'
import nodataUrl from '@/assets/nodata.png'
import AddRegisterType from '@/views/processing/register/components/addRegisterType.vue'
import { createProcessing, getProcessingTypeList } from '@/api/processing'
import { toArray, toMap } from '@/utils/dataType'
const router = useRouter()
try {
  getHeader()
}catch (error) {
  router.push('/login')
}
const store = useStore()
const warehouse = store.warehouse
const ownerRef = ref(null)
const ownerItem = ref({})
const ownerCode = ref('')
const date = ref(formatDate(new Date()))
const note = ref('')
const code=ref('')
const processingTypeList=ref([])
const processingTypeMap=ref({})
//添加类型
const addRegisterTypeRef=ref(null)
const typeList = ref([])
const dateTrueFalseBy = ref(false)
//选择货主
const onOwner = (item) => {
  ownerItem.value = item
  ownerCode.value = item.name
}
//选择日期
const dateConfirm = (e) => {
  date.value = formatDate(e)
  dateTrueFalseBy.value = false
}
//提交登记
const onConfirm = () => {
  if(!ownerCode.value){
    showNotify({ type: 'warning', duration: 3000, message: '请选择货主' })
    scanError()
    return
  }
  if(typeList.value.length==0){
    showNotify({ type: 'warning', duration: 3000, message: '请先添加单据类型' })
    scanError()
    return
  }
  if(!code.value){
    showNotify({ type: 'warning', duration: 3000, message: '请先添加单据信息' })
    scanError()
    return
  }

  showConfirmDialog({
    title: '温馨提示', message:'是否确认建单' })
    .then(() => {
    _createProcessing()
    }).catch(() => {})
}

const _createProcessing=()=>{
  const data={owner:ownerItem.value.id,ownerCode:ownerItem.value.code,note:note.value,warehouse,typeList:typeList.value,noList:toArray(code.value)}
  showLoading()
  createProcessing(data).then(res=>{
    closeLoading()
    scanSuccess()
    showConfirmDialog({
      title: '建单成功',
      message:`加工单号为：${res.data}`,
      confirmButtonText:'复制'
    })
      .then(() => {
        copyText(res.data)
      })
      .catch(() => {});
    reset()
  }).catch(err=>{
    scanError()
    closeLoading()
  })
}
const copyText=(txt) =>{
  const textarea = document.createElement('textarea');
  textarea.value =txt;
  document.body.appendChild(textarea);
  textarea.select();
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      showNotify({ type: 'success', duration: 3000, message: '已复制' })
    } else {
      console.error('复制失败');
    }
  } catch (err) {
    showNotify({ type: 'danger', duration: 3000, message: '复制失败' })
  } finally {
    document.body.removeChild(textarea);
  }
}
const reset=()=>{
  code.value=""
  typeList.value=[]
  note.value=""
  ownerCode.value=''
}
//添加类型
const addType=()=>{
  addRegisterTypeRef.value?.show(typeList.value)
}
const setProcessingType=(data)=>{
  typeList.value.push(data)
}
//转换类型名称
const getOperate=(operate)=>{
  const result = operate.map(item => processingTypeMap.value[item] || item)
  return result.join(',')
}
//获取类型
const _getProcessingTypeList=()=>{
  getProcessingTypeList().then(res=>{
    processingTypeList.value=res.data
    processingTypeMap.value=toMap(res.data,'code','name')
  })
}
const del=(item,index)=>{
  typeList.value.splice(index,1)
}
_getProcessingTypeList()
</script>
<style scoped lang="sass">
.register
  .register-content
    background: #fff
    padding: 10px
    font-size: 14px
    .add-type
      text-align: right
    .type-box
      text-align: left
      .type-title
        line-height: 30px
        color: #999
      .type-list
        border: 1px solid #e9e9e9
        border-radius: 6px
        padding: 5px 10px
        .type-item
          display: flex
          align-items: center
          border-bottom: 1px solid #e9e9e9

          padding: 3px 0
          .type-item-item
            flex: 1
          .type-item-operate
            width: 70px
            text-align: center
          .type-item-delete
            width: 70px
            text-align: center
            color: #ff4141
            text-decoration: underline
        .type-item:last-child
          border-bottom: none



</style>
