<template>
   <div class="cpr_step_cell">

       <!-- 每种输入框都需要的label -->
       <div v-if="!noHead" class="cell_label" :class="{'cell_label_border': ['timeSelect', 'placeSelect'].indexOf(cellData.inputType) != -1}">
           <div class="label_left">
                <div class="required_icon" v-if="cellData.nessesary">
                    <Icon name="icon-shoucang" color="#F68585" size="6px"></Icon>
                </div>
                <div class="label_text">{{cellData.labelText}}</div>
                <div class="label_tip" v-if="cellData.tipText" @click="showTip()">
                    <Icon name="icon-wenhao" color="#F68585" size="14px"></Icon>
                </div>
           </div>
            <!-- 时间选择 -->
           <div class="label_right" v-if="cellData.inputType == 'timeSelect' || cellData.inputType == 'timeRangeSelect'" @click="showTimeSelect=true">
               <div>{{contentText? contentText : cellData.placeHolder}}</div>
               <Icon class="time_icon" name="icon-rili" color="#6377FF" size="15px"></Icon>
           </div>
           <!-- 地址选择 -->
           <div class="label_right" v-if="cellData.inputType == 'placeSelect'" @click="showPlaceSelect=true">
               <div>{{contentText? contentText : cellData.placeHolder}}</div>
               <Icon class="time_icon" name="icon-fuwudiqiu" color="#6377FF" size="15px"></Icon>
           </div>
       </div>

       <slot></slot>
    
       <!-- 每种输入框的内容-->
       <!-- 单行文本框 -->
       <div class="cell_content" v-if="cellData.inputType=='text'">
           <input v-model="textText" type="text" :placeholder="cellData.placeHolder" @change="(e)=>textInput(e)">
       </div>
       <!-- 文本区域 -->
       <div class="cell_content_textarea" v-if="cellData.inputType=='textArea'">
           <textarea v-model="textAreaText" :placeholder="cellData.placeHolder" @change="(e)=>textInput(e, cellData.maxCount)"></textarea >
           <div class="cell_textarea_tip">
               <div></div>
               <div>{{textAreaLength}}/{{cellData.maxCount}}</div>
           </div>
       </div>
       <!-- 文件 -->
       <label :for="cellData.labelText" v-if="cellData.inputType=='file'" >
            <div class="cell_content" >
                <input @change="fileUpload" :id="cellData.labelText"  type="file" :placeholder="cellData.placeHolder" multiple hidden>
                {{cellData.placeHolder}}
                <Icon name="icon-xiayibu" color="#A7B5CD" size="16px"></Icon>
            </div>
       </label>
       <!-- 选择框 -->
       <div class="cell_content" v-if="cellData.inputType=='choose'" @click="showActionSheet=true">
           <div>{{contentText || cellData.placeHolder}}</div>
           <Icon name="icon-xiayibu" color="#A7B5CD" size="16px"></Icon>
       </div>
       <!-- 单选框 -->
       <div class="cell_content" v-if="cellData.inputType=='singleSelect'" >
           <van-radio-group v-model="singleSelect" direction="horizontal" @change="singleSelectChange">
             <van-radio v-for="item in cellData.selectOption" :key="item.value" :name="item.value" >{{item.text}}</van-radio>
           </van-radio-group>
       </div>
       <!-- 增加人员 -->
       <div class="add_people_btn" v-if="cellData.inputType=='addPeople'" @click="addPeople(cellData.jumpPath)">
           <Icon name="icon-jia-xianxingfangkuang" color="#A7B5CD" size="18px"></Icon>
           <span class="add_people_text">{{cellData.placeHolder}}</span> 
       </div>

        <!-- 下面是各种弹出框 -->
       <van-action-sheet v-model="showActionSheet" :actions="cellData.actions" cancel-text="取消" @select="onActionSelect" @cancel="showActionSheet=false" />
       <van-calendar loading="true" v-model="showTimeSelect" :min-date="new Date(1970, 1, 1)" :type="cellData.inputType == 'timeRangeSelect'?'range':'single'" color="#6377FF" @confirm="onTimeSelect" />
       <van-popup v-model="showPlaceSelect" position="bottom">
           <van-area title="选择地点" :area-list="areaList" :columns-num="2" @cancel="showPlaceSelect=false" @confirm="onPlaceSelect" />
       </van-popup>
   </div>
</template>

<script lang='ts'>
/**框架*/
import Vue from 'vue'
/**工具库*/
import SparkMD5 from "spark-md5";
import { areaList } from '@vant/area-data';
/**类型*/
/**组件*/
import Icon from '@/components/common/Icon.vue'
/**自定义方法*/

interface CprStepCellDataType {
    labelText: string,
    nessesary?: boolean,
    tipText?: string,
    placeHolder: string,
    // contentText?: any,
    actions?: Array<any>,
    inputType: string,
    fileTypeArray?: Array<string>
    maxCount?: number,
    selectOption?: Array<{text: string, value: number}>,
    areaList: any,
    fileListMaxCount?: number,
    jumpPath?: string,
}
export default Vue.extend({
    name:'',
    props: {
        cellData:{
            default: {} as CprStepCellDataType,
            required: true
        },
        contentText: {
            default: '',
        },
        noHead: {
            default: false
        }
    },
    data(){
        return {
            showActionSheet: false,
            showTimeSelect: false,
            singleSelect: this.contentText,
            showPlaceSelect: false,
            areaList,
            textText: this.contentText,
            textAreaText: this.contentText
        }
    },
    computed:{
        textAreaLength(): number{
            if(this.textAreaText){
                return this.textAreaText.length
            }else {
                return 0
            }
            
        }
    },
    components: {
        Icon
    },
    methods: {
        /**展示提示框 */
        showTip(){
            this.$dialog({
                title: '温馨提示',
                message: this.cellData.tipText,
            })
        },
        /**检查文件并计算hash */
        async fileUpload(e: { target: {files: File[], value: any} }){
            if(e.target?.files.length < 1) return;
            /**检查文件数量 */
            if(this.cellData.fileListMaxCount && e.target?.files.length > this.cellData.fileListMaxCount) {
                this.$toast(`最多上传${this.cellData.fileListMaxCount}个文件`) 
                return;
            }
            /**检查文件大小及类型 */
            for(let item of e.target?.files) {
                if(item.size > 200*1024*1024) {
                   this.$toast('单文件大小应小于200m') 
                   return;
                }
                const type_name = item.name.substring(item.name.lastIndexOf('.')+1, item.name.length).toUpperCase()
                if(this.cellData.fileTypeArray && this.cellData.fileTypeArray.indexOf(type_name) == -1){
                   this.$toast('不支持此类型文件') 
                   return;
                }
            }
            /**所有符合条件后才开始上传 */
            this.$toast.loading({
                message: 'hash计算中...',
                forbidClick: true,
            })
            for(let item of e.target?.files) {
                const fileHash = await this.hashCalc(item)
                console.log(item.size)
                const fileData = {
                    fileName: item.name,
                    fileHash,
                    file: item,
                    type: item.name.substring(item.name.lastIndexOf('.')+1, item.name.length).toLowerCase(),
                    fileUrl: '',
                    fileSize: item.size
                }
                this.$emit('fileListUpdata', fileData)
            }
            e.target.value = null
        },
        /**文件hash计算 */
        async hashCalc(file: File) {
            //分块计算hash
            const ab = await file.arrayBuffer();
            let chunkSize = 104857600;
            let chunks = Math.ceil(file.size / chunkSize);
            let currentChunk = 0;
            let spark = new SparkMD5.ArrayBuffer();
            while(currentChunk<chunks){
                const start = currentChunk * chunkSize,
                end = start + chunkSize >= file.size ? file.size : start + chunkSize;
                spark.append(Buffer.from(ab).slice(start,end))
                currentChunk ++
            }
            return spark.end()
        },
        /**下弹选择框好后, 传递出去 */
        onActionSelect(selected: any){
            this.$emit('onActionSelect', selected)
            this.showActionSheet = false
        },
        /**单行文本和文本域输入后，传递出去 */
        textInput(e: { target: HTMLInputElement }, maxCount?: number){
            if(maxCount && e.target.value.length > maxCount) {
                this.$toast(`不能超过${maxCount}字`)
                e.target.value = this.textAreaText.substring(0, 1000)
                this.textAreaText = this.textAreaText.substring(0, 1000)
            }
            this.$emit('onTextChange', e.target.value)
        },
        /**时间选择器确认后，传递出去*/
        onTimeSelect(e: Date | Date[]){
            this.showTimeSelect = false
            if(!Array.isArray(e)) {
                this.$emit('onTimeSelect', Number(e))
            }else if(Array.isArray(e)) {
                this.$emit('onTimeSelect', e.map((item)=>{return Number(item)}))
            }
            
        },
        /**地址选择确认后，传递出去 */
        onPlaceSelect(palce: Array<{code: string, name: string}>){
            this.showPlaceSelect = false
            this.$emit('onPlaceSelect', palce)
        },
        /**单选框触发改变时 */
        singleSelectChange(e:number){
            this.$emit('onSingleSelectChange', e)
        },
        /**添加人员 */
        addPeople(path: string | undefined){
            if(!path) {
                this.$emit('onAddPeople')
            } else {
                this.$router.push({path, query: {...this.$route.query}})
            }
        }
    }
})
</script>

<style scoped lang='less'>

.cpr_step_cell {
    color: #7388AB;
    font-size: 12px;
    .cell_label {
        height: 48px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .label_left {
            display: flex;
            align-items: center;
            .required_icon {
                margin-right: 5px;
            }
            .label_text {
                margin-right: 6px;
                line-height: 12px;
            }
            .label_tip {

            }
        }
        .label_right {
            display: flex;
            align-items: center;
            .time_icon {
                margin-left: 10px;
                margin-bottom: 3px;
            }
        }
    }
    .cell_label_border {
        border-bottom: 2px solid #F5F5F5;
    }
    .cell_content {
        min-height: 40px;
        border-bottom: 2px solid #F5F5F5;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        input {
            width: 80%;
        }
        input::input-placeholder {
            color: #7388AB;
        }
        textArea {
            border: 1px solid #F8F8F8;
            box-shadow: 2px 2px 5px 0px rgba(213, 213, 213, 0.5);
            width: 100%;
            min-height: 130px;
        }
    }
    .add_people_btn {
        height: 40px;    
        border-radius: 10px;
        border: 1px solid #F5F5F5;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px auto;
        .add_people_text {
            font-size: 14px;
            margin-left: 7px;
        }
    }
    .cell_content_textarea {
        min-height: 40px;
        font-size: 14px;
        textArea {
            padding: 8px;
            border: 1px solid #F8F8F8;
            box-shadow: -2px -2px 5px 0px rgba(213, 213, 213, 0.5);
            width: 100%;
            min-height: 130px;
        }
        .cell_textarea_tip {
            display: flex;
            justify-content: space-between;
        }
    }
}
// 更改弹出层样式
.van-action-sheet__cancel, .van-action-sheet__item {
    background-color: #fff;
    color: #2B446C;
}
.van-action-sheet__item:active {
  background-color: #F5F5F5;
}
.van-action-sheet__gap {
    background-color: #2B446C;
    height: 2px;
}

</style>