<template>
  <page-header-wrapper>
    <a-card style="box-sizing:border-box;padding:20px;margin-top: 10px;" v-if="vdata.productDetail.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>
              <div style="display:flex;flex-direction:row">
                <a-col :span="11" v-if="$access('ENT_MCH_APP_LIST')">
                  <a-form-item label="关联应用" required>
                    <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.productDetail.bindingAppList">{{
                          vdata.productDetail.bindingAppList.indexOf(item.appId as any) === -1 ? '未关联' : '已关联' }}</span>

                      </a-select-option>
                    </a-select>
                  </a-form-item>
                  <span class="jeepay-tip-text jeepay-tip-title">(线上场景需要通过应用获取各种能力并进行开发对接（如APP支付、分账、代付等），当前进件商户需要与应用进行关联。
                    <a target="_blank" href="https://shouyinbei.yuque.com/rv7pt7/xczlxt/dgxuxxgl17vsvwvl?singleDoc#"
                      style="font-weight: 600">了解应用</a> )</span>

                </a-col>
                <a-button style="margin-left: 15px;" type="primary" @click="submitPay(2)"><plus-outlined />创建应用</a-button>

              </div>
            </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>-->
          <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)"
              v-if="vdata.productDetail.bindingApp == 0">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
          </div>
          <a-divider />
          <div>
            <a-table :columns="vdata.columns" :data-source="vdata.costRule" :pagination="false"
              :row-selection="{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" :label-col="vdata.orderLabelCol"
                :rules="vdata.orderRules">
                <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-form-item label="姓名" required>
                  <a-input v-model:value="vdata.orderFormState.contactsName" />
                </a-form-item>
                <a-form-item label="手机号" required>
                  <a-input v-model:value="vdata.orderFormState.contactsTel" maxlength="11"
                    onkeyup="value=value.replace(/\D+/,'')" />
                </a-form-item>

                <a-form-item label="特殊资质">
                  <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="getImg(item)">查看示例</a>
                    </div>
                  </div>

                </a-form-item>
              </a-form>
            </div>

          </div>
          <!-- <div class="title-content" v-if="vdata.orderType == 1">
            <div class="product-content" v-html="vdata.productContent" />
          </div> -->
          <div class="title-content" v-if="vdata.orderType == 2">
            <h3>汇款充值到账时效</h3>
            <p>
              汇款充值后，充值到账时间为<b style="color: #ff0000">下个工作日内24点前</b>。<br>
              注：实际到账时间请以三方支付公司充值时间为准。<br>

              下列操作可能导致资金无法正常入账：<br>

              （1）央行大额支付系统关闭期间发起汇款<br>

              （2）收款方账户户名、收款方账号、收款银行等关键信息输入错误造成无法入账<br>

              （3）银行端汇款渠道问题，客户提交的汇款资金未成功转出或到账<br>

              （4）使用非本公司同名银行账户或个人银行账户进行充值<br>
            </p>
            <h3> 为什么汇款充值未到账？</h3>
            <p>
              资金未到账可能有两种原因：<br>

              1）我司还未收到充值资金；需要检查资金是否成功转出或收款方银行还未到账，到账时间视银行情况而定。<br>

              2）充值资金在退回过程中 ；没有填写正确的收款账户、单笔转账超过限额等原因会导致汇款充值失败被退回，退回具体到账时间视银行情况而定。<br>
            </p>
          </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: 10px;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>

    <a-modal v-model:visible="vdata.confirmVisible" title="支付订单" @ok="handleOk" width="700px">
      <div class="orderModel">
        <div class="magin-5">订购信息</div>
        <div class="orderInfo orderModelFlex justify-between magin-b-10">
          <div class="orderModelFlex">
            <div class="w100">订购服务</div>
            <div>
              {{vdata.orderFormState.costRule[0].versionName}}
            </div>
          </div>

          <div class="orderModelFlex">
            <div class="w100">订购规格</div>
            <div>{{vdata.orderFormState.costRule[0].validTime===-1?'永久':vdata.orderFormState.costRule[0].validTime}}</div>
          </div>
        </div>
        <div class="orderInfo orderModelFlex justify-between">
          <div class="orderModelFlex">
            <div class="w100">订购价格</div>
            <div>{{vdata.orderFormState.costRule[0].sellingPrice===0?'免费':vdata.orderFormState.costRule[0].sellingPrice}}</div>
          </div>

          <div class="orderModelFlex">
            <div class="w100">订购数量</div>
            <div>1</div>
          </div>
        </div>
        <div class="magin-5">订购人</div>
        <div class="orderUser orderModelFlex justify-between">
          <div class="orderModelFlex">
            <div class="w100">订购方信息</div>
            <div>{{vdata.orderFormState.contactsName}}</div>
          </div>

          <div class="orderModelFlex">
            <div class="w100">联系电话</div>
            <div>{{vdata.orderFormState.contactsTel}}</div>
          </div>
        </div>
        <div class="magin-5">收款方信息</div>
        <div class="payee orderModelFlex justify-between">
          <div class="orderModelFlex magin-b-10">
            <div class="w100">收款方信息</div>
            <div>蚂蚁金服(杭州)网络技术</div>
          </div>

          <div class="orderModelFlex">
            <div class="w100">收款账户</div>
            <div>13593993781</div>
          </div>
        </div>
        <div>
          <div class="orderModelFlex">
            <div class="w100">联系电话</div>
            <div>95188</div>
          </div>
        </div>
        <div class="magin-5">订购价格</div>
        <div class="orderPrice orderModelFlex justify-between">
          <div class="orderModelFlex">
            <div class="w100">订购总价</div>
            <div style="color:#f97246">{{vdata.orderFormState.costRule[0].sellingPrice===0?'免费':vdata.orderFormState.costRule[0].sellingPrice}}</div>
          </div>
        </div>

        <div class="magin-5">特殊资质</div>
        <div class="orderPrice orderModelFlex justify-between">
          <div class="orderModelFlex">
            <div class="w100">名称</div>
            <div>{{vdata.orderFormState.specialCertificationText[0].certificationName || ''}}</div>
          </div>
          <div class="orderModelFlex">
            <div class="w100">特殊资质文件</div>
            <div>
              <img style="width:50px; height: 50px" :src="vdata.orderFormState.specialCertificationText[0].certificationUrl || '' ">
            </div>
          </div>
        </div>

      </div>
    </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, API_URL_PRODUCT_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 vdata = reactive({
  visible: false, // 对话框
  confirmVisible:false, //订单确认对话框
  productId: "",
  toastContent: '', // 对话框内容
  toastTitle: '', // 对话框标题
  mchAppList: [] as any, // app列表
  filteredAppInfoList: [] as any, // app列表
  mchStoreList: [] as any, // 门店列表
  appId: '', // 已选择的appId
  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统一收银台
  productContent: "",
  productDetail: {
    bindingApp: 1,
    bindingAppList: [] as any
  } as any,
  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 }],
  },
  orderRules: {
    name: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  },

  orderFormState: {
    contactsName: '',
    contactsTel: '',
    remark: '',
    actualPrice: '', //订单总售价，单位分
    price: '', //订单总售价，单位分
    costRule: [] as any,
    appId: "",
    productId: "",
    type: "",
    packageorproduct: "",
    specialCertificationText:[], //回传特殊资质
  } as any ,

  orderLabelCol: { style: { textAlign: 'left', width: '20%' } },

  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',
    },
    // {
    //   title: '数量',
    //   key: 'count',
    //   dataIndex: 'count',
    //   slots: { customRender: "count" },
    // },
    // {
    //   key: 'countPrice',
    //   dataIndex: 'countPrice',
    //   title: '总价',
    //   slots: { customRender: "countPrice" },
    // },
  ],
  costRule: [],
  certificationColumns:[
      {
        title: '名称',
        key: 'certificationName',
        dataIndex: 'certificationName',
      },
      {
        key: 'certificationUrl',
        dataIndex: 'certificationUrl',
        title: '图片',
        slots: { customRender: "certificationUrl" },
      },
      {
        title: '类型',
        key: 'inputType',
        dataIndex: 'inputType',
      },
  ],
  specialCertificationText:[{certificationName:'' as any,UserUrl:'' as any,}],
})

const state = reactive({
  selectedRowKeys: [],
})

function getImg(item){
  $viewerApi({images: [item.certificationUrl]})
}


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 handleOk(){

}
const infoFormModel = ref()

const onSelectionChange = (selectedRowKeys, selectedRows) => {
  console.log(selectedRowKeys,selectedRows)
  vdata.orderFormState.costRule = selectedRows
}

const emit = defineEmits(['itemRender'])

const table=ref() as any
function submitPay(type) {
  if (type == 1) {
    vdata.costRule = []
    vdata.orderFormState={}
    vdata.appId=""
    vdata.orderFormState.costRule=[]
    state.selectedRowKeys = [];
    emit('itemRender', { 'table': 'table', 'productId': vdata.productId, 'type': 1 },false)
  } else if (type == 2) {
    emit('itemRender', { 'table': 'table', 'productId': vdata.productId, 'type': 4 })
  } else {

    if (formState.checked) {
      let count = 0
      let hxCount = 0
      vdata.orderFormState.costRule.forEach((item: any) => {
        count += item.sellingPrice * item.count
        hxCount += item.lineationPrice * item.count
      })
      vdata.orderFormState.actualPrice = count as any
      vdata.orderFormState.price = hxCount as any
      vdata.orderFormState.appId = vdata.appId as any
    } else {
      $infoBox.message.error('请勾选产品服务合同')
      return false
    }

    if (vdata.productDetail.bindingApp === 1 && vdata.appId === '') {
      $infoBox.message.error('请选择关联应用')
      return false
    }

    if (vdata.orderFormState.costRule.length < 1) {
      $infoBox.message.error('请勾选订购产品')
      return false
    }
    if (vdata.orderFormState.contactsName === '') {
      $infoBox.message.error('请输入联系人姓名')
      return false
    }
    if (vdata.orderFormState.contactsTel === '') {
      $infoBox.message.error('请输入联系人手机号')
      return false
    }

    formSage.value
      .validate()
      .then(() => {
        vdata.orderFormState.productId = vdata.productId as any
        vdata.orderFormState.appId = vdata.appId
        vdata.orderFormState.type = 3 as any
        vdata.orderFormState.packageorproduct = 0 as any
        vdata.orderFormState.specialCertificationText=vdata.specialCertificationText
        // vdata.confirmVisible=true
        emit('itemRender', vdata.orderFormState)
      })
      .catch((error) => {
        console.log('error', error)
      })
  }
}

// function handleOk(){
//   emit('itemRender', vdata.orderFormState)
// }
function check() {
  formState.checked = !formState.checked
}
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 getOrderType(type) {
  vdata.orderType = type
}
function show(productId) {
  vdata.productId = productId
  getMchApp()
  getDetail()
}

function getDetail() {
  if (!vdata.productId) {
    return false;
  }
  req.list(API_URL_PRODUCT_DETAIL_LIST, { productId: vdata.productId }).then(data => {
    vdata.productDetail = data
    if (!data.bindingAppList) {
      vdata.productDetail.bindingAppList = [] as any;
    }
    if(data.specialCertificationText!==undefined){
      vdata.specialCertificationText=data.specialCertificationText
    }
    //给初始值
    console.log(data.productText)
    if(data.productText!==undefined){
      vdata.costRule = data.productText.map((item) => {
        item.count = 1
        return item
      })
    }
  })
}

function getMchApp() {
  req.list(API_URL_MCH_APP, { pageSize: -1, state: 1 }).then(res => {
    vdata.mchAppList = res.records
    vdata.filteredAppInfoList = res.records
  })
}
// const handleCilckSelect = (appId) => {
//   vdata.filteredAppInfoList.map((item) => {
//     if (item.appId === appId) {
//       vdata.orderFormState.appName = item.appName + '[' + item.appId + ']'
//     }
//   })
// }
//应用搜索
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-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;
}

.orderModel{
  .orderInfo{}
  .orderUser{}
  .payee{}
  .orderPrice{}
  .justify-between{
    justify-content: space-between;
  }
}
.orderModelFlex{
  display: flex;
  flex: 1;
}
.w100{
  width: 100px;
  color: #ccc;
}
.magin-5{
  margin: 8px 0;
}
.magin-b-10{
  margin-bottom: 10px;
}
</style>
