<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" class="ant-table-btn" @click="getWomenIdCardInfo">身份证识别</a-button>
                        <a-row :gutter="16">
                            <a-col :span="12">
                                <a-form-model-item label="姓名" prop="womanName">
                                    <a-input placeholder="请输入姓名" :disabled="disabled"
                                             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="请选择"
                                              :disabled="disabled">
                                        <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"
                                             :disabled="disabled"></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"
                                                   :disabled="disabled">
                                        <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="formData.oncePregnant==1">
                                    <a-input v-toInt placeholder="请输入" v-model="formData.pregnantNum"
                                             :disabled="disabled"></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" class="ant-table-btn" @click="getMenIdCardInfo">身份证识别</a-button>
                        <a-row :gutter="16">
                            <a-col :span="12">
                                <a-form-model-item label="姓名" prop="manName">
                                    <a-input placeholder="请输入姓名" v-model="formData.manName"
                                             :disabled="disabled"></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="请选择"
                                              :disabled="disabled">
                                        <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"
                                             :disabled="disabled"></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"
                                             :disabled="disabled"></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
                                                :disabled="disabled"
                                                :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"
                                             :disabled="disabled"></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"
                                                   :disabled="disabled"
                                                   style="width: 100%"/>
                                </a-form-model-item>
                            </a-col>
                            <!--<a-col :span="21" :offset="3" v-if="routerParams.routerFlag == 'update'">
                                <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" v-if="routerParams.routerFlag == 'update'">
                                <a-form-model-item :wrapperCol="{span: 23}">
                                    <div style="border: 1px dashed #EEEEEE">
                                       <img style="width: 100%;height: 160px" :src="formData.consentUrl">
                                    </div>
                                </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">请选择要发放的叶酸种类
                            </a-button>
                            <a-table :dataSource="formData.provideRecordList" rowKey="id" :pagination="false"
                                     class="table_input tab_error modal_table"
                                     style="margin-top: 10px"
                                     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">
                                    <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;"
                                                     @change="getChangeRecord(record)"
                                            >

                                            </a-input>
                                        </a-form-model-item>
                                    </template>
                                </a-table-column>
                                <a-table-column title="操作" align="center" 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-button class="ant-table-btn" size="small">删除</a-button>
                                        </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="请输入备注，最多可输入500字" v-model="formData.remarks" :rows="5"
                                        :maxLength="500"></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 class="ant-table-btn" @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, GetUserInfoByCardDevice} 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')),
                spinning: false,
                // 弹窗内表单
                formData: {
                    womanName: undefined,
                    womenCertificateType: '1',
                    womenIdCard: undefined,
                    oncePregnant: '',
                    pregnantNum: undefined,
                    manName: undefined,
                    menCertificateType: '1',
                    menIdCard: undefined,
                    telephone: undefined,
                    presentCode: undefined,
                    nowAddress: undefined,
                    signedMode: '2',
                    parentDate: moment(new Date()).format('yyyy-MM-DD'),
                    provideDate: moment(new Date()).format('yyyy-MM-DD'),
                    provideDoctorId: undefined,
                    provideRecordList: [],
                    remarks: undefined,
                },
                disabled: false,
                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, prod) => {
                                let index;
                                for (let key in prod) {
                                    let keyArr = key.split(".");
                                    index = Number(keyArr[1]);
                                }
                                if (value == '' || value == undefined) {
                                    callback()
                                }
                                let number = this.formData.provideRecordList[index].number
                                if (value <= number) {
                                    callback()
                                } else {
                                    callback(new Error('超出当前库存！'));
                                }
                            },
                        },
                    ]
                },
                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.disabled = true;
                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.formData = {}
                    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(),
                        consentUrl: data.consentUrl,
                        parentDate: data.parentDate,
                        provideDate: moment(new Date()).format('yyyy-MM-DD'),
                        provideDoctorId: data.provideDoctorId,
                        provideRecordList: data.provideRecordList,
                        remarks: data.remarks,
                    }
                    this.spinning = false
                }).catch(() => {
                    this.spinning = false
                })
            },
            getWomenIdCardInfo() {
                GetUserInfoByCardDevice().then(res => {
                        let {cardno, name, address} = res;
                          this.formData.womanName = name
                          this.formData.womenIdCard = cardno
                        })
            },
            getMenIdCardInfo() {
                GetUserInfoByCardDevice().then(res => {
                    let {cardno, name, address} = res;
                    this.formData.manName = name
                    this.formData.menIdCard = cardno
                })
            },
            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'] = item.areaLevel >= 5;
                    })
                    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() {
                if (this.routerParams.routerFlag == "update") {
                    this.$router.push("/Home/folviteApply");
                    closedDetail('/inStock/addMaterialDistribution', '/Home/folviteApply');
                } else {
                    this.$router.push("/Home/folviteDistribution");
                    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;
        }
    }
    .modal_table {
        .ant-form-item {
            margin-bottom: 0px!important;
        }
    }
</style>
