<template>
  <page-header-wrapper>
    <a-card style="box-sizing:border-box;padding:20px;margin-top: 10px;"  v-if="vdata.packageDetail.bindingApp == 1">
      <div  style="width: 100%;" class="paydemo">
        <div class="paydemo-type-content">
          <div class="paydemo-type-name article-title paydemo-type-name-div">
            <div class="article-title-top1">关联应用</div>
            <div class="article-title-top2 div-top-title-tio2" @click="submitPay(1)">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
          </div>
          <a-divider />
          <div class="title-content" v-if="vdata.orderType == 1">
            <a-form layout="vertical" :rules="vdata.rule">
              <a-row justify="space-between" type="flex">
                <a-col :span="24"  v-if="vdata.packageDetail.bindingApp == 1">
                  <a-form-item v-if="props.configMode != 'mch'" label="用户名称" name="userName">
                    <JeepaySearchInfoInput v-model:value="vdata.orderFormState['userName']" @itemRender="getUser" placeholder="用户名称" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="$access('ENT_MCH_APP_LIST')">
                  <div style="flex-direction:row">
                  <a-form-item label="关联应用" name="appId"  v-if="$access('ENT_MCH_APP_LIST')">
                    <a-select v-model:value="vdata.appId" placeholder="选择应用" show-search @search="handleAppidChange" :filter-option="false">
                      <a-select-option v-for="(item) in vdata.filteredAppInfoList" :key="item.appId">
                        {{ item.appName }}
                        [{{ item.appId as any }}]
<!--                        <span v-if="vdata.packageDetail.bindingAppList">{{-->
<!--                            vdata.packageDetail.bindingAppList.indexOf(item.appId as any) === -1 ? '未关联' : '已关联' }}</span>-->
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                 <a-button style="margin: 10px;" type="primary" @click="submitPay(2)"><plus-outlined />创建应用</a-button>
                  </div>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </div>
    </a-card>

    <a-card style="box-sizing:border-box;padding:20px;margin-top: 10px;">
      <div  style="width: 100%;" class="paydemo">
        <div class="paydemo-type-content">
          <div class="paydemo-type-name article-title">
            订购信息
          </div>
          <a-divider />
          <div class="title-content">
            <div>
              <a-table :columns="vdata.columns" :data-source="vdata.costRule" :pagination="false"
                       :row-selection="{selectedRowKeys:vdata.versionName,type: 'radio', onChange: onSelectionChange}" row-key="versionName">
                <template #customTitle>
                <span>
                  方案名称
                </span>
                </template>
                <template #versionName="{ text }">
                  <div style="display: flex; align-items: center;">
                    <span>{{ text }}</span>
                  </div>
                </template>

                <template #validTime="{ text }">
                  <div style="display: flex; align-items: center;">
                    <span>{{ text === -1 ? '长期' : text }}</span>
                  </div>
                </template>
                <template #sellingPrice="{ text }">
                <span>
                  {{ text }}
                </span>
                </template>

                <template #lineationPrice="{ text }">
                <span>
                  {{ text }}
                </span>
                </template>

                <!--              <template #count="{ record }">-->
                <!--                <a-input-number :min="1" :max="100000" v-model:value="record.count" />-->
                <!--              </template>-->
                <template #countPrice="{ record }">
                <span style="color: #f00;">{{ record.sellingPrice == '免费' ? '免费' : record.count * record.sellingPrice
                    + '元' }}</span>
                </template>
              </a-table>
              <div style="width: 50%; margin-left: 30px; margin-top: 30px;">
                <a-form ref="formRef" :model="vdata.orderFormState"
                        :rules="vdata.orderRules" layout="vertical">

                  <a-form-item label="备注(可选)" name="remark">
                    <a-textarea v-model:value="vdata.orderFormState.remark" :rows="1" />
                  </a-form-item>
                  <div style="margin-bottom: 20px;">
                    <span style="font-size: 18px; font-weight: 900;margin-right: 22px;">提供联系人信息</span><span
                      style="color: #858585;">用于订购后,服务商与你取得联系</span>
                  </div>
                  <!-- <div style="display: flex; margin: 30px 0;">
                    <div style="width: 20%;">订购应用:</div>
                    <div>{{ vdata.orderFormState.appName }}</div>
                  </div> -->
                  <a-row justify="space-between" type="flex">
                    <a-col :span="12" >
                      <a-form-item label="用户名称" name="userName"  v-if="props.configMode != 'mch' && vdata.packageDetail.bindingApp != 1">
                        <JeepaySearchInfoInput v-model:value="vdata.orderFormState['userName']" @itemRender="getUser" placeholder="请输入用户名称" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="12" >

                    </a-col>
                    <a-col :span="12" >
                    <a-form-item label="姓名" required>
                      <a-input v-model:value="vdata.orderFormState.contactsName" placeholder="请输入姓名"/>
                    </a-form-item>
                    </a-col>
                    <a-col :span="12" >

                    </a-col>
                    <a-col :span="12" >
                    <a-form-item label="手机号" required>
                      <a-input v-model:value="vdata.orderFormState.contactsTel" maxlength="11"
                               onkeyup="value=value.replace(/\D+/,'')" placeholder="请输入手机号"/>
                    </a-form-item>
                    </a-col>
                  </a-row>
                  <a-form-item label="特殊资质" v-if="vdata.packageDetail.certification == 1">
                    <div style="display: flex;">
                      <div class="upload-box" v-for="(item,index) in vdata.specialCertificationText" :key="index" style="margin-right: 20px;text-align: center;">
                        <div>{{item.certificationName}}</div>
                        <JeepayUpload v-model:src="item.UserUrl" bizType="applyment" :imgSize="1"  class="upload-box-img"/>
                        <a class="color-box-span" @click="getImgURL(item)">查看示例</a>
                      </div>
                    </div>
                  </a-form-item>
                </a-form>
              </div>

            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-card style="box-sizing:border-box;padding:20px;margin-top: 10px;">
      <a-form  ref="formSage" :model="formState" :rules="sageRules" >
        <div  style="width: 100%;" class="paydemo">
          <div class="product-bottom"  >
            <a-button style="margin-left: 15px;border-radius: 5px;"  type="primary" @click="submitPay(0)">立即开通</a-button>
                <a-form-item name="checked" style="margin-left: 10px;">
                  <a-checkbox  class="checked_size" v-model:checked="formState.checked" @click.stop.prevent="check">我已阅读并同意</a-checkbox>
                  <a class="forge-password checked_size" @click.stop.prevent="servicePaymentFlund">《产品服务合同》</a>
                </a-form-item>
          </div>
        </div>
      </a-form>
    </a-card>

    <a-modal v-model:visible="vdata.visible" :title="vdata.toastTitle" :footer="null" width="70%">
      <div style="height: 70vh; overflow: auto;" v-html="vdata.toastContent" />
    </a-modal>
  </page-header-wrapper>
</template>

<script setup lang="ts">
import {
  API_URL_MCH_APP,
  API_URL_MCH_STORE_LIST,
  req,
  $payTest,
  $payTestOrder,
  $getTreaty,
  API_URL_PACKAGE_DETAIL_LIST
} from '@/api/manage' // 接口
import {ref, onMounted, reactive, getCurrentInstance, nextTick, defineComponent, defineEmits} from 'vue'
import {useRoute} from 'vue-router'
// 获取全局函数
const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties
const { $viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const route = useRoute()
let formState: any = reactive({
  checked: false,
})

const props = defineProps({
  configMode: { type: String, default: '' },   // 模式
})
const vdata =  reactive({
  orderRules:{},
  visible: false, // 对话框
  packageId:"",
  toastContent: '', // 对话框内容
  toastTitle: '', // 对话框标题
  mchAppList: [] as any, // app列表
  filteredAppInfoList: [] as any, // app列表
  mchStoreList: [] as any, // 门店列表
  storeId: '', // 已选择的门店ID
  appPaywayList: [] as any, // 商户app支持的支付方式
  currentWayCode: '', // 以何种方式进行支付，默认是微信二维码
  currentPayDataType: '', // 支付参数
  mchOrderNo: '', // 模拟商户订单号
  authCode: '', // 条码的值
  autoPosExtra: {}, // 智能POS参数
  paytestAmount: 0.01, // 支付金额，默认为0.01
  amountInput: false, // 自定金额输入框是否展示
  noConfigText: false, // 尚无任何配置分割线提示文字
  divisionMode: 0, // 订单分账模式
  orderRemarks: '', // 订单标题
  orderNumber: '', // 订单标题
  orderType:1,
  divisionMode1:0.01,  //默认支付金额绑定
  webCashierIsShow: true,  // 是否显示web统一收银台
  packageDetail:{
    bindingAppList:"" as  any,
    bindingApp:"" as any,
    certification:"" as any
  },
  appId:"",
  columns: [
    {
      dataIndex: 'versionName',
      key: 'versionName',
      slots: { title: 'customTitle', customRender: 'versionName' },
    },
    {
      title: '周期',
      dataIndex: 'validTime',
      key: 'validTime',
      slots: {customRender: 'validTime' },
    },
    {
      title: '单价',
      key: 'sellingPrice',
      dataIndex: 'sellingPrice',
    },
    {
      title: '划线价',
      key: 'lineationPrice',
      dataIndex: 'lineationPrice',
    },
  ],
  orderFormState: {
    contactsName: '',
    contactsTel: '',
    remark: '',
    actualPrice: '', //订单总售价，单位分
    price: '', //订单总售价，单位分
    costRule: [] as any,
    appId: "",
    productId: "",
    type: "",
    packageorproduct: "",
    specialCertificationText:[], //回传特殊资质
  } as any ,
  costRule: [],
  rule: {
    appId: [{ required: true, message: '请选择应用', trigger: 'blur' }],
    // storeId: [{ required: true, message: '请选择门店', trigger: 'blur' }],
    // orderNumber: [{ required: true, message: '请输入正确的金额，最多支持2位小数，单笔充值金额区间100-50000', trigger: 'blur', type: 'number', min: 0.01, max: 50000 }],
  },
  specialCertificationText:[{certificationName:'' as any, UserUrl:'' as any, }],
  certificationColumns:[
    {
      title: '名称',
      key: 'certificationName',
      dataIndex: 'certificationName',
    },
    {
      key: 'certificationUrl',
      dataIndex: 'certificationUrl',
      title: '图片',
      slots: { customRender: "certificationUrl" },
    },
    {
      title: '类型',
      key: 'inputType',
      dataIndex: 'inputType',
    },
  ],
  orderLabelCol: { style: { textAlign: 'right', width: '10%' } },
  versionName:[] as any,
})

let formSage = ref()
const sageRules: any = reactive({
  checked: [{ type: 'boolean', required: true, message: '请勾选产品服务合同', trigger: 'check' },{
    validator: (rule, value) => {
      if(formState.checked){
        return Promise.resolve()
      }else{
        return Promise.reject('请勾选产品服务合同')
      }
    }
  }]
})
function getUser(e){
  vdata.orderFormState.userNo = e.mchNo
  vdata.orderFormState.mchNo = e.mchNo
  vdata.orderFormState.userName = e.mchShortName
}
const infoFormModel = ref()
onMounted(()=>{

})
const onSelectionChange = (selectedRowKeys, selectedRows) => {
  // console.log(selectedRowKeys,selectedRows)
  console.log(selectedRowKeys,'selectedRowsselectedRows')
  vdata.versionName = [selectedRowKeys]
  vdata.orderFormState.costRule = selectedRows
}
function onSelectioncertificationChange(){
  console.log(1111111)
}
const emit = defineEmits(['itemRender'])
function submitPay(type){

  if(type == 1){
    emit('itemRender',{'table':'table','packageId':vdata.packageId,'type':1})
  }else if(type == 2){
    emit('itemRender',{'table':'table','packageId':vdata.packageId,'type':4})
  }else{
    // vdata.orderFormState.costRule=vdata.costRule


    if (!formState.checked){
      $infoBox.message.error('请勾选产品服务合同')
      return false
    }
    let count = 0
    let hxCount = 0
    vdata.orderFormState.costRule.forEach((item: any) => {
      count += item.sellingPrice * item.count
      hxCount += item.lineationPrice * item.count
    })
    if (vdata.packageDetail.bindingApp === 1 && vdata.appId === '') {
      $infoBox.message.error('请选择关联应用')
      return false
    }



    if (vdata.orderFormState.costRule.length < 1) {
      $infoBox.message.error('请勾选订购产品')
      return false
    }
    if (vdata.specialCertificationText.length < 1 && vdata.packageDetail.certification == 1) {
      $infoBox.message.error('请输入特殊资质')
      return false
    }
    vdata.orderFormState.actualPrice=vdata.orderFormState.costRule[0].sellingPrice
    vdata.orderFormState.price=vdata.orderFormState.costRule[0].lineationPrice

    if (vdata.orderFormState.contactsName === '') {
      $infoBox.message.error('请输入联系人姓名')
      return false
    }
    if (vdata.orderFormState.contactsTel === '') {
      $infoBox.message.error('请输入联系人手机号')
      return false
    }
    console.log(vdata.orderFormState.mchNo,'vdata.orderFormState.mchNo')
    if (props.configMode != 'mch' && !vdata.orderFormState.mchNo) {
      $infoBox.message.error('选择用户')
      return false
    }
    formSage.value
        .validate()
        .then(() => {
          vdata.orderFormState.packageId = vdata.packageId as any
          vdata.orderFormState.appId = vdata.appId
          vdata.orderFormState.type = 3 as any
          vdata.orderFormState.packageorproduct = 1 as any
          emit('itemRender', {
            type:3,
            packageId:vdata.orderFormState.packageId,
            packageOrProduct:1,
            appId:vdata.orderFormState.appId,
            mchNo:vdata.orderFormState.mchNo as any,
            userNo:vdata.orderFormState.mchNo as any,
            costRule:vdata.costRule,
            specialCertificationText:vdata.specialCertificationText,
            contactsName:vdata.orderFormState.contactsName,
            remark:vdata.orderFormState.remark,
            contactsTel:vdata.orderFormState.contactsTel,
            actualPrice:vdata.orderFormState.actualPrice,
            price:vdata.orderFormState.price,
          })
        })
        .catch((error) => {
          console.log('error', error)
        })
  }
}

function servicePaymentFlund() {
  vdata.visible = true
  vdata.toastTitle = '产品服务合同'
  // message.success('服务协议')
  getTreaty('产品服务合同')
}
const getTreaty = (name) => {
  $getTreaty().then(res => {
    name === '产品服务合同' ? vdata.toastContent = res.servicePaymentFlund
        : vdata.toastContent = res.privacyPolicy
  })
}
function changeAppId(){

}

function check() {
  formState.checked = !formState.checked
}

function  getOrderType(type){
  vdata.orderType = type
}
function show(packageId){
  vdata.packageId = packageId
  getDetail()
  if(props.configMode == 'mch'){
    getMchApp()
  }
}

function getDetail(){
  if(!vdata.packageId){
    return false;
  }
  req.list(API_URL_PACKAGE_DETAIL_LIST, { packageId: vdata.packageId }).then(data => {
    vdata.packageDetail = data
    vdata.orderFormState=data

    if (!data.bindingAppList) {
      vdata.packageDetail.bindingAppList = [] as any;
    }
    if(data.specialCertificationText!==undefined){
      vdata.specialCertificationText=data.specialCertificationText
    }
    //给初始值
    if(data.packageText!==undefined){
      vdata.costRule = data.packageText.map((item) => {
        item.count = 1
        return item
      })
      vdata.versionName = [vdata.costRule[0]['versionName'] as any]
      vdata.orderFormState.costRule = vdata.costRule
      console.log(vdata.orderFormState.costRule.length,'vdata.orderFormState.costRule')
    }

  })
}


function getMchApp(){
  const  data = { pageSize: -1, state: 1 ,mchNo:""}
  if(vdata.orderFormState.userNo){
    data.mchNo = vdata.orderFormState.userNo;
  }
  req.list(API_URL_MCH_APP, data).then(res => {
    vdata.mchAppList = res.records
    vdata.filteredAppInfoList = res.records
  })
}

const getImgURL=(item)=>{
  $viewerApi({images: [item.certificationUrl]})
}


//应用搜索
const handleAppidChange = (value) => {
  vdata.filteredAppInfoList = [];
  console.log(vdata.mchAppList,'vdata.storeList')
  vdata.mchAppList.forEach((item: { appName: string | any[], appId: string | any[] },index) => {
    if (item.appName.includes(value) || item.appId.includes(value) ) {
      vdata.filteredAppInfoList.push(vdata.mchAppList[index]);
    }
  });
};


defineExpose({ show })
</script>

<style scoped lang="css">
.article-title-span{
  padding: 0 10px;
}
.span-active{
  color: #1677ff;
}
.span-active::after{
//content: '' !important;
//display: block !important;
//background-color: rgba(44, 110, 246, 1) !important;
//border-radius: 45px !important;
//width: 22px !important;
//height: 4px !important;
}
.paydemo-type-name-div{
  display: flex;
}
.article-title-top1{
  width: 50%;
}
.article-title-top2{
  width: 50%;
  text-align: right;
}
.article-title-top2 bottom{
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  box-shadow: 0 2px 0 rgba(0,0,0,.015);
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5715;
  padding: 4px 25px !important;
  text-align: center;
}
h4{
  color: #333;
  height: 30px;
  padding: 20px 0;
}
.title-content h3{
  font-weight: bold;
}
.title-content p{
  color: #9b9b9b;
  font-family: PingFangSC-Regular;
  font-size: 14px;
  line-height: 22px;
  margin-bottom: 10px;
  white-space: pre-line;
}
.paydemo .paydemo-type-content{
  padding: unset !important;
}
.paydemo-address{
  display: block !important;
  background: #f9f9f9;
  border-radius: 5px;
}
.paydemo-address p{
}

.paydemo-address-div{
  width: 600px;
  display: flex;
}
.span1{
  width: 80px !important;
  text-align:right;
  padding: 15px 10px 0 10px;
}
.span2{
  width: 280px !important;
  text-align:left;
  padding: 15px 5px 0 15px;
}
.span3{
  padding: 5px 0 0 0;
  width: 100px !important;
  text-align:right;
  color: #1677ff;
}
.layui-form{
  margin-top:50px;
}
.paydemo-form-item{
  padding-top:10px ;
  padding-bottom:10px ;
}
.paydemo .paydemo-form-item{
  margin-bottom: 45px;
}
.table-head-layout{
  margin-bottom: unset !important;
  margin-right: 10px;
}
.paydemo-form-item-input{
  display: grid !important;
}

.product-bottom{
  display: flex;
}

.product-bottom-span{
  padding: 10px 25px;
  background: #2C6EF6;
  color: #ffffff;
  border-radius: 11px;
}
.product-bottom-check{
  margin-left: 20px;
  padding-top: 10px;
}
.article-title{
  font-weight: bold;
  font-size: 18px;
}
.ant-card-body{
  background: #f0f0f0 !important;
}
</style>
