<template>
    <div>
        <a-spin tip="加载中..." :spinning="spinning">
            <a-card>
            <div style="font-size: 18px;font-weight: 600">
                <span>叶酸发放登记</span>
            </div>
            <a-form-model ref="formRef" :model="formData" :rules="formRules" :labelCol="{span: 6}"
                          :wrapperCol="{span: 16}">

                <div style="margin: 30px 0px">
                    <div class="divider_my"><span class="midText">居民信息</span></div>
                </div>
                <div style="clear: both"></div>
                <a-card size="small" :headStyle="{background: '#FAFAFA'}">
                    <div slot="title">
                        <img class="title_img" src="../../../../../static/images/user_info_index.png">
                        <span class="title_font">女方信息</span>
                    </div>
                    <a-button slot="extra">身份证识别</a-button>
                    <a-row :gutter="16">
                        <a-col :span="12">
                            <a-form-model-item label="姓名" prop="womanName">
                                <a-input placeholder="请输入姓名" v-model="formData.womanName"></a-input>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="证件类型" prop="womenCertificateType">
                                <a-select v-model="formData.womenCertificateType" placeholder="请选择">
                                    <a-select-option v-for="item in certificateTypeList"
                                                     :key="item.enumValue" :value="item.enumValue"
                                    >
                                        {{item.enumName}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-model-item label="证件号码" prop="womenIdCard">
                                <a-input placeholder="请输入证件号码" v-model="formData.womenIdCard"></a-input>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="是否曾经怀孕" prop="oncePregnant">
                                <a-radio-group v-model="formData.oncePregnant" @change="onChangePregnant">
                                    <a-radio :value="1">
                                        否
                                    </a-radio>
                                    <a-radio :value="2">
                                        是
                                    </a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="孕次" prop="pregnantNum" v-if="womanPregnant">
                                <a-input v-toInt placeholder="请输入" v-model="formData.pregnantNum"></a-input>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-card>
                <a-card size="small" :headStyle="{background: '#FAFAFA'}" style="margin-top: 16px">
                    <div slot="title">
                        <img class="title_img" src="../../../../../static/images/user_info_index.png">
                        <span class="title_font">男方信息</span>
                    </div>
                    <a-button slot="extra">身份证识别</a-button>
                    <a-row :gutter="16">
                        <a-col :span="12">
                            <a-form-model-item label="姓名" prop="manName">
                                <a-input placeholder="请输入姓名" v-model="formData.manName"></a-input>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="证件类型" prop="menCertificateType">
                                <a-select v-model="formData.menCertificateType" placeholder="请选择">
                                    <a-select-option v-for="item in certificateTypeList"
                                                     :key="item.enumValue" :value="item.enumValue"
                                    >
                                        {{item.enumName}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-model-item label="证件号码" prop="menIdCard">
                                <a-input placeholder="请输入证件号码" v-model="formData.menIdCard"></a-input>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-card>
                <a-card size="small" :headStyle="{background: '#FAFAFA'}" style="margin-top: 16px">
                    <div slot="title">
                        <img class="title_img" src="../../../../../static/images/user_info_index.png">
                        <span class="title_font">其他信息</span>
                    </div>
                    <a-row :gutter="16">
                        <a-col :span="24">
                            <a-form-model-item label="联系电话" prop="telephone" :labelCol="{span: 3}"
                                               :wrapperCol="{span: 8}">
                                <a-input placeholder="请输入联系电话" v-model="formData.telephone"></a-input>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="现住地址" prop="presentCode" :labelCol="{span: 3}"
                                               :wrapperCol="{span: 20}">
                                <!--<a-input placeholder="请输入现住地址" v-model="formData.presentCode"></a-input>-->
                                <a-cascader v-model="formData.presentCode"
                                            change-on-select
                                            :options="areaInfo"
                                            :fieldNames="fieldNames"
                                            :load-data="loadAreaData"
                                            @click.native="initLoadAreaData"
                                            placeholder="请选择"/>
                            </a-form-model-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-model-item label="详细地址" prop="nowAddress" :labelCol="{span: 3}"
                                               :wrapperCol="{span: 20}">
                                <a-input placeholder="请输入详细地址" v-model="formData.nowAddress"></a-input>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="签署方式" prop="signedMode">
                                <a-select v-model="formData.signedMode" placeholder="请选择" disabled>
                                    <a-select-option v-for="item in signedModeList"
                                                     :key="item.enumValue" :value="item.enumValue"
                                    >
                                        {{item.enumName}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item label="签署日期" prop="parentDate">
                                <a-date-picker v-model="formData.parentDate" format="YYYY-MM-DD" style="width: 100%"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="21" :offset="3">
                            <a-form-model-item  :wrapperCol="{span: 23}">
                                <a-card class="book" :headStyle="{background: '#FAFAFA'}">
                                    <div slot="title" style="text-align: center;padding: 10px 0px">
                                        <span style="color: #262626;font-size: 14px">知情同意书</span>
                                    </div>
                                    <div>
                                    <div v-html="bookHtmlContent.content">

                                    </div>
                                    </div>
                                </a-card>
                            </a-form-model-item>
                        </a-col>

<!--                        <a-col :span="21" :offset="3">
                            <a-form-model-item  :wrapperCol="{span: 23}">
                                <div style="border: 1px dashed #EEEEEE">
                                    <div class="sign">签字</div>
                                    <vue-signature-pad
                                            id="signature"
                                            width="100%"
                                            height="200px"
                                            ref="signaturePad"
                                            :options="options"
                                    />
                                    <div class="opt">
                                        <a-button @click="reWrite">重写</a-button>
                                        <a-button type="primary" @click="save" style="margin-left: 10px">确定签字</a-button>
                                    </div>
                                </div>
                            </a-form-model-item>
                        </a-col>-->
                    </a-row>
                </a-card>
                <div style="margin: 30px 0px">
                    <div class="divider_my"><span class="midText">发放信息</span></div>
                </div>
                <div style="clear: both"></div>

                <a-col :span="12">
                    <a-form-model-item label="发放日期" prop="provideDate">
                        <a-date-picker v-model="formData.provideDate" format="YYYY-MM-DD" style="width: 100%"/>
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item label="发放医生" prop="provideDoctorId">
                        <a-select v-model="formData.provideDoctorId" placeholder="请选择">
                            <a-select-option v-for="item in doctorInfoList"
                                             :key="item.id" :value="item.id"
                            >
                                {{item.staffName}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
                <a-col :span="21" :offset="3">
                    <a-form-model-item  :wrapperCol="{span: 23}">
                        <a-button type="primary" @click="openStockModel" style="margin-bottom: 10px">请选择要发放的叶酸种类</a-button>
                        <a-table  :dataSource="formData.provideRecordList" rowKey="id" :pagination="false" class="table_input tab_error"
                                 bordered>
                            <a-table-column title="供应商名称" data-index="supplierName"></a-table-column>
                            <a-table-column title="品牌" data-index="brandName"></a-table-column>
                            <a-table-column title="批次号" data-index="batchNumber"></a-table-column>
                            <a-table-column title="当前库存" data-index="number"></a-table-column>
                            <a-table-column title="发放数量" width="190px" fixed="right">
                                <template slot-scope="text, record, index">
                                    <a-form-model-item :prop="'provideRecordList.' + index + '.sendNumber'"
                                                       :rules="formRules.sendNumber" class="tab_input_r">
                                        <a-input type="number"
                                                 v-toInt
                                                 v-model="record.sendNumber"
                                                 placeholder="请输入发放数量"
                                                 style="width: 150px;margin-top: 20px"
                                                 @change="getChangeRecord(record)"
                                        >

                                        </a-input>
                                    </a-form-model-item>
                                </template>
                            </a-table-column>
                            <a-table-column title="操作" align="center" fixed="right" width="70px">
                                <template slot-scope="text, record, index">
                                    <!-- <a-button type="link" class="table_delbtn" @click="deleteGoodsList(index)">删除</a-button> -->
                                    <a-popconfirm
                                            title="确定移除该物资吗？"
                                            ok-text="是"
                                            cancel-text="否"
                                            @confirm="confirm(index)"
                                    >
                                        <a href="#" class="table_delbtn">删除</a>
                                    </a-popconfirm>
                                </template>
                            </a-table-column>
                        </a-table>
                    </a-form-model-item>
                </a-col>
                <a-col :span="24">
                    <a-form-model-item label="备注" prop="remarks" :labelCol="{span: 3}" :wrapperCol="{span: 20}">
                        <a-textarea placeholder="请输入备注" v-model="formData.remarks" :rows="5"></a-textarea>
                    </a-form-model-item>
                </a-col>
            </a-form-model>

<!-- 选择叶酸种类弹框-->
                <div>
                <in-stock-manage-info ref="inStockManageInfo" @selectedIdList="getChecked" v-if="readyGetChecked"></in-stock-manage-info>
                </div>
            <div style="text-align: center;margin-top: 16px">
                <a-button @click="goBack">取消</a-button>
                <a-button type="primary" :loading="spinning" @click="addMaterialDis" style="margin-left: 8px">发放</a-button>
            </div>
            </a-card>
        </a-spin>
    </div>

</template>

<script>
    import {checkPhone, closedDetail, getEnumByFlag} from "../../../utils/common";
    import moment from 'moment'
    import InStockManageInfo from "./inStockManageInfo";

    let vm = this
    let recordInfo = {}
    export default {
        components: {InStockManageInfo},
        data() {
            return {
                unitInfo: JSON.parse(window.sessionStorage.getItem('networkInfo')),
                routerParams: [],
                spinning: false,
                // 弹窗内表单
                formData: {
                    womanName: undefined,
                    womenCertificateType: '1',
                    womenIdCard: undefined,
                    oncePregnant: 1,
                    pregnantNum: undefined,
                    manName: undefined,
                    menCertificateType: '1',
                    menIdCard: undefined,
                    telephone: undefined,
                    presentCode: undefined,
                    nowAddress: undefined,
                    signedMode: '1',
                    parentDate: undefined,
                    provideDate: undefined,
                    provideDoctorId: undefined,
                    provideRecordList: [],
                    remarks: undefined,
                },
                formRules: {
                    womanName: [
                        {required: true, message: '请输入姓名'}
                    ],
                    womenCertificateType: [
                        {required: true, message: '请选择证件类型'}
                    ],
                    womenIdCard: [
                        {required: true, message: '请输入证件号码'}
                    ],
                    oncePregnant: [
                        {required: true, message: '请选择是否曾经怀孕'}
                    ],
                    pregnantNum: [
                        {required: true, message: '请输入孕次'}
                    ],
                    manName: [
                        {required: true, message: '请输入姓名'}
                    ],
                    menCertificateType: [
                        {required: true, message: '请选择证件类型'}
                    ],
                    menIdCard: [
                        {required: true, message: '请输入证件号码'}
                    ],
                    telephone: [
                        {required: true, message: '请输入联系电话'},
                        {validator: checkPhone},
                    ],
                    presentCode: [
                        {required: true, message: '请选择选择现住地址'}
                    ],
                    nowAddress: [
                        {required: true, message: '请输入详细地址'}
                    ],
                    signedMode:  [
                        {required: true, message: '请选择签署方式'}
                    ],
                    parentDate:  [
                        {required: true, message: '请选择签署日期'}
                    ],
                    provideDate: [
                        {required: true, message: '请选择发放日期'}
                    ],
                    provideDoctorId: [
                        {required: true, message: '请选择发放医生'}
                    ],
                    sendNumber: [
                        {required: true, message: '请输入发放数量'},
                        {
                            validator: (rule, value, callback) => {
                                if (value == '' || value == undefined) {
                                    callback()
                                }
                                if (value <= recordInfo.number) {
                                    callback()
                                } else {
                                    callback(new Error('超出当前库存！'));
                                }
                            },
                        },
                    ],
                    remarks: [
                        {required: true, message: '请输入备注'}
                    ],
                },
                womanPregnant: false,//是否怀孕
                options: {
                    penColor: "#000",//画笔颜色
                },
                certificateTypeList: [],
                signedModeList: [],
                bookHtmlContent: '',
                modalinfo: {
                    selectedRowKeys: []
                },
                readyGetChecked: true,
                doctorInfoList: [],
                areaInfo:[],
                fieldNames: {
                    label: 'areaName',
                    value: 'areaCode',
                    children: 'children'
                },
                routerParams: {}
            }
        },
        created() {
            this.routerParams = this.$route.query
            this.certificateTypeList = getEnumByFlag('folacin_resident_info_certificate_type')
            this.signedModeList = getEnumByFlag('folacin_resident_info_signed_mode')
            this.getBookHtmlContent()
            this.getAllDoctorList()
            if (this.routerParams.routerFlag == 'update') {//从申请过来的发放
                 this.getStockListDetail()
            } else {//由新增过来的发放
                this.initLoadAreaData()
            }
        },
        methods: {
            getStockListDetail() {
                this.spinning = true
                let par = {
                    residentId: this.routerParams.id
                }
                this.$api.folviteDistributionManage.fetchFolviteDistributionDetail(par).then(({data = [], code}) => {
                    this.areaInfo = [{areaCode: data.presentCode, areaName: data.presentCodeName}]
                    this.formData = {
                        womanName: data.womanName,
                        womenCertificateType: data.womenCertificateType.toString(),
                        womenIdCard: data.womenIdCard,
                        oncePregnant: +data.oncePregnant,
                        pregnantNum: data.pregnantNum,
                        manName: data.manName,
                        menCertificateType: data.menCertificateType.toString(),
                        menIdCard: data.menIdCard,
                        telephone: data.telephone,
                        presentCode: [data.presentCode],
                        nowAddress: data.nowAddress,
                        signedMode: data.signedMode.toString(),
                        parentDate: data.parentDate,
                        provideDate: data.provideDate,
                        provideDoctorId: data.provideDoctorId,
                        provideRecordList: data.provideRecordList,
                        remarks: data.remarks,
                    }
                    this.spinning = false
                }).catch(() => {
                    this.spinning = false
                })
            },
            initLoadAreaData() {
                this.areaInfo = []
                this.loadAreaData([{areaCode: 0}])
            },
            loadAreaData(selectedOptions) {
                const targetOption = selectedOptions[selectedOptions.length - 1];
                targetOption.loading = true;
                this.$api.common.fetchAreaByCode({areaCode: targetOption.areaCode}).then(({data = []}) => {
                    targetOption.loading = false;
                    data.forEach(item => {
                        item['isLeaf'] = false
                    })
                    if (targetOption.areaCode == 0) {
                        this.areaInfo = [...data]

                    } else {
                        targetOption.children = [...data]
                        this.areaInfo = [...this.areaInfo]
                    }
                })
            },
            getBookHtmlContent() {//获取用户知情书模板
                this.$api.common.fetchConsentInfo().then(({data}) => {
                    if (this.$api.utils.isBlank(data)){
                        this.bookHtmlContent={content:""}
                    }else {
                        this.bookHtmlContent = data;
                    }
                })
            },
            getAllDoctorList() {
                this.$api.common.fetchAllDoctor().then(({data}) => {
                    this.doctorInfoList = data
                    })
            },
            //------签字-----------
            reWrite() {
                this.$refs.signaturePad.clearSignature();
            },
            save() {
                const {isEmpty, data} = this.$refs.signaturePad.saveSignature();
                // console.log(isEmpty);
                // console.log(data);
            },

            getChecked(val) {
                this.readyGetChecked = false
                this.$refs.inStockManageInfo.visible = false
                this.modalinfo.selectedRowKeys = [...val]
                this.getSelectedMedical(val)
            },

            // 删除药具
            confirm(index) {
                this.formData.provideRecordList.splice(index, 1);
            },
            //获取改变的当前项
            getChangeRecord(record) {
                recordInfo = record
            },
            getSelectedMedical(val) {//获取被选中的药具
                if (val.length > 0) {
                    let par = {
                        idList: val.join(',')
                    }
                    this.$api.stockManage.fetchMedicalListByIds(par).then(({data = []}) => {
                        this.formData.provideRecordList = data
                    })
                }

            },
            addMaterialDis() {//发放
                let vm = this
                this.$refs.formRef.validate(valid => {
                    if (valid) {
                        if (this.formData.provideRecordList.length === 0) {
                            this.$message.warning('发放叶酸不能为空！');
                        } else {
                            this.spinning = true;
                            let params ={}
                            this.formData.provideRecordList.forEach(item => {
                                item.stockId = item.id
                            });
                            const {parentDate, provideDate,presentCode,provideDoctorId, ...others} = vm.formData

                            let parentTime = moment(parentDate).format('YYYY-MM-DD')
                            let provideTme = moment(provideDate).format('YYYY-MM-DD')
                            let presentCodeInfo = presentCode[presentCode.length -1]
                            let provideDoctorInfo = vm.doctorInfoList.filter(item => item.id == provideDoctorId)
                             params ={
                                parentDate: parentTime,
                                provideDate: provideTme,
                                presentCode: presentCodeInfo,
                                provideDoctorId: provideDoctorInfo[0].id,
                                provideDoctorName: provideDoctorInfo[0].staffName,
                                ...others
                            }
                            if (this.routerParams.routerFlag == 'update') {
                                params.applyId = this.routerParams.id
                                this.$api.folviteApplyManage.addFolviteDistributionByApply(params).then(({code}) => {
                                    this.spinning = false;
                                    if (code === 'SUCCESS') {
                                        this.$message.success('发放成功！');
                                        this.goBack()
                                    }
                                }).catch(() => {
                                    this.spinning = false
                                })
                            } else {
                                this.$api.folviteDistributionManage.fetchAddFolviteDistribution(params).then(({code}) => {
                                    this.spinning = false;
                                    if (code === 'SUCCESS') {
                                        this.$message.success('发放成功！');
                                        this.goBack()
                                    }
                                }).catch(() => {
                                    this.spinning = false
                                })
                            }
                        }
                    }
                });
            },
            onChangePregnant(e) {
                let val = e.target.value
                if (val == 2) {
                    this.womanPregnant = true
                } else {
                    this.womanPregnant = false
                }
            },
            //打开库存弹框
            openStockModel() {
                this.readyGetChecked = true
                let vm = this
                this.$nextTick(() => {
                    vm.$refs.inStockManageInfo.visible = true
                })

            },
            goBack() {
                closedDetail('/inStock/addMaterialDistribution', '/Home/folviteDistribution')
            }
        }
    }
</script>

<style scoped lang="less">
    .title_img {
        display: inline-block;
        width: 24px;
        height: 24px;
        margin-top: -5px;
        margin-left: 20px;
    }

    .title_font {
        font-family: PingFang SC;
        color: #595959;
        font-weight: 600;
        font-size: 16px;
        line-height: 22px;
        margin: 16px 0px 16px 18px;
    }

</style>

<style lang="less">

    .book {
        .ant-card-head-title {
            padding: 0px!important;
        }
    }
    .sign {
        position: absolute;
        background: #FFF1F0;
        border-radius: 0px 0px 24px 0px;
        width: 60px;
        height: 40px;
        padding: 0px 16px;
    }

    .opt {
        float: right;
        margin-top: 10px;
    }
     .table_input {
          .ant-table-tbody > tr > td {
             padding: 5px!important;
             overflow-wrap: break-word;
         }
     }

</style>
