<template>
    <div>
        <div style="display: flex;align-items: center;justify-content: space-between;" v-if="isShow">
            <div>
                <a-input-search v-model:value="value" placeholder="请输入商品名" style="width: 200px;margin-left: 20px;"
                    @search="onGetSearch" />
            </div>
            <div>
                <a-button type="primary" block @click="onCreatePay">新建支付项</a-button>
            </div>
        </div>
        <div style="margin-top: 10px;" v-if="isShow">
            <a-table :dataSource="list" :columns="columns" :pagination="pagination" @change="tableChange" :scroll="{ y:  'calc(100vh - 270px)' }">
                <template #bodyCell="{ column, record }">
                    <div v-if="column.key == 'picurl'">
                        <div style="display:flex;align-items: center;">
                            <div>{{ record.subject }}
                            </div>
                        </div>
                    </div>
                    <div v-else-if="column.key == 'status'" style="width:80px;">
                        <div v-if="record.status == 0" style="color: rgb(12, 191, 33);width:80px;"  >
                            正常
                        </div>
                        <div v-else-if="record.status == 1" style="color: #e6a23c;width:80px;">
                            预警额度
                        </div>
                        <div v-else style="color: #f56c6c;width:80px;">
                            风控
                        </div>
                    </div>
                    <div v-if="column.key == 'payment'">
                       {{record.payment/100}}
                    </div>

                    <div v-if="column.key == 'tags'" style="display:flex;">
                        <a-button type="primary" @click="onEdit(record)" style=";width: 80px;" >编辑</a-button>
                        <a-button type="primary" style="margin-left: 10px;width: 80px;" @click="onCopy(record)">支付链接</a-button>
                        <!-- <a-button type="primary" style="margin-left: 20px;">统计</a-button> -->
                        <a-popconfirm title="确定下架这条数据" ok-text="确定" cancel-text="取消" @confirm="onDel(record)" style=";width: 80px;">
                            <a-button type="primary" style="margin-left: 10px">删除</a-button>
                        </a-popconfirm>
                    </div>
                     <div v-if="column.key == 'time' && (record.starttime >= new Date())" style="color: #DDD222;">
                      {{moment(record.starttime).format('YYYY-MM-DD HH:mm')}}
                     </div>
                     <div v-else-if="column.key == 'time' && (record.starttime<new Date())" style="color: red;">
                      {{moment(record.starttime).format('YYYY-MM-DD HH:mm')}}
                     </div>
                </template>
            </a-table>
        </div>
        <div v-else>
            <div style="display:flex">
                <a-button class="small left" @click="onBack">
                <template #icon>
                    <LeftOutlined />
                </template>
                </a-button>
            </div>
            <CreatePay @onBack="onBack"></CreatePay>
        </div>
        <a-modal v-model:visible="visible" title="编辑" @ok="handleOk" :width="1000" >
            <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }"
                autocomplete="off"  >
                <a-form-item label="选择商品" name="subject" :label-col="{ span: 2 }" labelAlign="left">
                    <div style="width:100%;display: flex;align-items: center;">
                    <a-select v-model:value="formState.subject" mode="multiple" style="width: 100%" placeholder="请选择商品" @focus="onSubSearch"  @search="onSubSearch" @select="onSelect" @popupScroll="popupScroll">
                    <a-select-option   v-for="item,index in listArray" :itemKey="item" :value="item.subject" :label="index" :key="index">
                       <span>{{item.subject}}</span> 
                        </a-select-option>
                    </a-select>
                    </div>
                </a-form-item>
                <a-form-item label="项目描述" name="shortname" :label-col="{ span: 2 }" labelAlign="left">
                    <a-input v-model:value="formState.shortname" placeholder="请输入商品描述" />
                </a-form-item>
                <a-form-item label="支付金额" name="price" :label-col="{ span: 2 }" labelAlign="left">
                    <a-radio-group v-model:value="formState.paymentmodel" name="radioGroup" class="pay">
                        <div style="display: flex;height: 35px;">
                            <a-radio value="0" style="width:150px;" >商品默认金额</a-radio>
                            <a-input-number style="width:200px;height: 35px;" :value="formState.price"  :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="value => value.replace(/\$\s?|(,*)/g, '')" :disabled="true"/>
                            <div style="width:50px;">元</div>
                        </div>
                        <div style="display: flex;height: 35px;margin-top: 20px;">
                            <a-radio value="1" style="width:150px;">自定义金额</a-radio>
                            <a-input-number style="width:200px;height: 35px;" v-model:value="formState.payment"  :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                            :parser="value => value.replace(/\$\s?|(,*)/g, '')"/>
                            <div style="width:50px;">元</div>
                        </div>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="支付前填写手机号" name="price" :label-col="{ span: 3 }" labelAlign="left">
                    <div style="display: flex;">
                        <a-switch v-model:checked="formState.fullphone" />
                    </div>
                </a-form-item>
                <a-form-item label="结束时间" name="price" :label-col="{ span: 2 }" labelAlign="left">
                    <div style="display:flex">
                        <a-date-picker v-model:value="value4" :format="dateFormat"
                            :disabledDate="disabledDate" />
                        <a-time-picker style="margin-left: 20px;" v-model:value="value5" format="HH:mm" />
                    </div>
                </a-form-item>
                <a-form-item label="信息备注" name="price" :label-col="{ span: 2 }" labelAlign="left">
                    <div style="display:flex">
                        <a-input v-model:value="formState.remark" placeholder="请填写备注" />
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, defineExpose, onMounted,reactive } from 'vue';
import { SelectProps,message } from 'ant-design-vue';
import { getUid } from '@/utils/userInfo'
import moment from 'moment';
import { onUpdateGoodsPay, onfindby,onfindWX,onfindAli,onDelectgoodpay,onFindbyLikeName,onFindBysub} from '@/api/index'
import CreatePay from './components/createpay/index.vue'
import dayjs, { Dayjs } from 'dayjs';
import useClipboard from 'vue-clipboard3'
import { LeftOutlined} from "@ant-design/icons-vue";
const dateFormat = 'YYYY/MM/DD';
let listValue = ref<any>([])
const { toClipboard } = useClipboard()
const disabledDate = (current: any) => {
    return current && current < moment().startOf("day")
}
const uid =getUid()
const value = ref<string>('');
const checkboxValue = ref<any>([])
const optionss = ref<Array<Object>>([])
const options = [...Array(25)].map((_, i) => ({ value: (i + 10).toString(36) + (i + 1) }))
let list = ref()
let listArray = ref<any>([])
let isShow = ref(true)
let formState = ref<any>({
})
const pagination = reactive({
    total:0,
    page:1,
    defaultPageSize:10,
    showSizeChanger:true,
    pageSizeOptions: ['5', '10', '15', '20'],
    onShowSizeChange:(current:any, pageSize:any)=>pageSize = pageSize
})
const optionsWithDisabled = [
    { value: '微信', label: '1' },
    { label: '2', value: '支付宝' },
    { label: '3', value: '京东白条' },
    { label: '4', value: '花呗' }
];
const columns = [
    {
        title: '支付项目名称',
        dataIndex: 'subject',
        key: 'subject',
         width: 130,
    },
    {
        title: '绑定商品编号',
        dataIndex: 'goodsid',
        key: 'goodsid',
    },
    {
        title: '商品价格',
        dataIndex: 'payment',
        key: 'payment',
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
         width: 100,
    },
    {
        title: '创建人',
        dataIndex: 'userid',
        key: 'userid',
    },
    {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
    },
    {
        title: '操作',
        dataIndex: 'tags',
        key: 'tags',
    },
    // {
    //     title: '生效时间',
    //     dataIndex: 'time',
    //     key: 'time',
    // },
]
const visible = ref<boolean>(false);
const value2 = ref<any>(dayjs('2015/01/01', dateFormat))
const value3 = ref<any>()
const value4 = ref<any>(dayjs('2015/01/01', dateFormat))
const value5 = ref<any>()
const showModal = () => {
    visible.value = true;
};
const handleOk =async(e: MouseEvent) => {
    const uid =getUid()
    const starttime  =  moment(new Date()).format('YYYY-MM-DDTHH:mm:[00][Z]')
    const expireendtime  = (moment(value4.value.$d).format('YYYY-MM-DD'))+(moment(value5.value.$d).format('THH:mm:[00][Z]'))
    formState.value.fullphone = formState.value.fullphone?'0':'1'
    formState.value.payment=  formState.value.payment*100
    const params={
        ...formState.value,
        uid,
    }
    const data:any = await onUpdateGoodsPay(params)
    if(data.state == 1){
     visible.value = false;
     onSearch()
    }
};
const onGetSearch= async() => {
    const params = {
      size:pagination.defaultPageSize,
      page:pagination.page ,
      uid:getUid(),
      subject:value.value
    }
   const data =await onFindBysub(params)
   list.value = data.data.goods
   pagination.total = data.data.count
}
const onEdit = (e: any) => {
    console.log(e,'e');
    
        formState.value= {
            ...e
        }
        value2.value = dayjs(moment(e.starttime).format(('YYYY/MM/DD')), dateFormat)
        value3.value =  dayjs(moment(e.starttime).format(('HH:mm')), 'HH:mm')
        value4.value =  dayjs(moment(e.expireendtime).format(('YYYY-MM-DD')), dateFormat)
        value5.value =  dayjs(moment(e.expireendtime).format(('HH:mm')), 'HH:mm')
        formState.value.payment = formState.value.payment/100
        formState.value.paymentmodel = '1'
         formState.value.fullphone = formState.value.fullphone?true:false
        showModal()
}
const onSearch = async () => {
    const params = {
        size:pagination.defaultPageSize,
         page:pagination.page ,
        name: value.value,
        uid: getUid()
    }
    const data = await onfindby(params)
    list.value = data.data.goods
    pagination.total = data.data.count
};
const tableChange=async(e:any)=>{
  let queryData = {
      current_page:e.current,//当前页数
      per_page:e.pageSize//每页显示条数
  };
  const params = {
        size:queryData.per_page,
        page:queryData.current_page ,
        uid: getUid()
    }
    const data = await onfindby(params)
    list.value = data.data.goods
    pagination.total = data.data.count
}
const onBack = (e: Number) => {
    isShow.value = !isShow.value;
    onSearch()
};
const onCreatePay = async () => {
    isShow.value = !isShow.value
}
const onCopy = async(e:any) => {
    console.log(e,'e');
    
    const value = localStorage.getItem('url') || ''
     try {
        await toClipboard(`${value}/#/?ditch=${uid}&goodsid=${e.id}&phone=${e.fullphone}`)
        message.success('复制成功')
      } catch (e) {
        console.error(e)
      }
}
const onSet = async(index:string)=>{
    const uid =getUid()
    let data:any ={}
    if (index == '1') {
     data = await onfindWX(uid);
    } else if (index == '2') {
    data = await onfindAli(uid);
    }
    list.value = data.data.goods
    pagination.total = data.data.count
}
const onDel = async (e: any) => {
    const prarms = {
        uid:getUid(),
        goodspayid:e.id
    } 
    const data:any = await onDelectgoodpay(prarms)
    if(data.state == 1){
        await onSearch()
    }
}
const onFinish = (values: any) => {
    console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};

const onSelectCheckboxValue = (e: any, index: any) => {
    checkboxValue.value[index] = e
}
const onSelect =(e:any,opt:any)=>{
    formState.value.subject = ''
    const goodspayditch = formState.value.goodspayditch
    const id = formState.value.id
    formState.value ={
        goodspayditch:goodspayditch,
        ...opt.itemKey,
        id
    }
    formState.value.price = formState.value.price/100
    formState.value.paymentmodel= '1'
    
}
const onSubSearch = async(value:any)=>{
    const uid = getUid();
    const params = {
        name: value.target?'':value,
        size:10,
        page:1,
        uid,
    };
    const data = await onFindbyLikeName(params);
    listArray.value = data.data.goods
    pagination.value.total =data.data.count
}
const popupScroll = ()=>{
    console.log(1);
}
onMounted(async () => {
    onSearch()
})
defineExpose({
    size: ref<SelectProps['size']>('middle'),
    value1: ref('a1'),
    options,
    value,
    isShow,
    visible,
    formState,
    checkboxValue,
    optionsWithDisabled,
    dateFormat,
    listValue,
    list,
    value2,
    value3,
    value4,
    value5,
    uid,
    pagination,
    optionss,
    columns,
    popupScroll,
    onSet,
    onSearch,
    onGetSearch,
    onEdit,
    onCreatePay,
    onBack,
    onCopy,
    onDel,
    showModal,
    handleOk,
    onSelect,
    disabledDate,
    onFinish,
    onFinishFailed,
    onSelectCheckboxValue
})
</script>
<style lang="less" scoped>
.small {
    border: none;
    height: 30px;
    width: 50px;
  }

  .left {
    border-left: 1px solid rgb(236, 236, 236);
    border-top: 1px solid rgb(236, 236, 236);
    border-bottom: 1px solid rgb(236, 236, 236);
    border-right-width: 80%;
    border-right: 1px solid rgb(236, 236, 236);
    border-bottom-left-radius: 25px;
    border-top-left-radius: 25px;
  }
</style>