<template>
    <!-- <el-drawer :visible.sync="drawerVisible" size="75%" :with-header="false" @closed="closeDrawer"> -->
    <div>
        <div class="header">
            {{ isEdit ? '编辑合同' : '新增合同' }}
            <!-- <i class="el-icon-close" @click="closeDrawer"></i> -->
        </div>
        <div class="container">
            <el-form :model="formData" :rules="addFormValidRules" ref="form" class="contract-form">
                <el-descriptions :column="3" border class="contract-description-form">
                    <el-descriptions-item labelClassName="required" label="母合同名称" :span="3"
                        v-if="parseInt(formData.contractNature) === 2">
                        <el-form-item prop="contractParent">
                            <el-select v-model="formData.contractParent" :style="{ width: '100%' }"
                                placeholder="请选择母合同名称">
                                <el-option v-for="(item, index) in contractParentList" :key="item.contractId"
                                    :value="item.contractId" :label="item.contractName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同名称" :span="2" labelClassName="required"
                        content-class-name="my-content">
                        <el-form-item prop="contractName">
                            <el-input placeholder="请输入合同名称" v-model="formData.contractName"></el-input>
                        </el-form-item>

                    </el-descriptions-item>
                    <el-descriptions-item label="合同性质" labelClassName="required">
                        {{ contractNatures[formData.contractNature] }}
                    </el-descriptions-item>
                    <el-descriptions-item label="合同乙方" labelClassName="required" :disabled="isEdit">
                        <el-form-item prop="contractPaetyb">
                            <el-input placeholder="请输入合同名称合同乙方" :disabled="isEdit" v-model="formData.contractPaetyb">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同编号" labelClassName="required" :disabled="isEdit">
                        <el-form-item prop="contractNumber">
                            <el-input placeholder="请输入合同编号" v-model="formData.contractNumber" :disabled="isEdit"></el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同类型" labelClassName="required">
                        <el-form-item prop="typeId">
                            <el-select v-model="formData.typeId" :style="{ width: '100%' }" placeholder="请选择合同类型">
                                <el-option v-for="(item, index) in contractTypeList" :key="item.id" :value="item.id"
                                    :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-descriptions-item>

                    <el-descriptions-item label="客户名称(甲方)" labelClassName="required">
                        <el-form-item prop="contractFirstParty">
                            <el-input placeholder="请输入客户名称(甲方)" :disabled="isEdit"
                                v-model="formData.contractFirstParty"></el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="甲方签订人" labelClassName="required">
                        <el-form-item prop="firstParty">
                            <el-input placeholder="请输入甲方签订人" :disabled="isEdit" v-model="formData.firstParty">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="客户联系电话" labelClassName="required">
                        <el-form-item prop="firstPartyPhone">
                            <el-input placeholder="请输入客户联系电话" :disabled="isEdit" v-model="formData.firstPartyPhone">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>

                    <el-descriptions-item label="客户联系地址" labelClassName="required">
                        <el-form-item prop="firstPartyAddress">
                            <el-input placeholder="请输入客户联系地址" :disabled="isEdit" v-model="formData.firstPartyAddress">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同开始日期" labelClassName="required">
                        <el-form-item prop="contractStartTime">
                            <el-date-picker align="right" type="datetime" :style="{ width: '100%' }"
                                placeholder="请输入合同签订时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                                v-model="formData.contractStartTime" :disabled="isEdit">
                            </el-date-picker>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同结束日期" labelClassName="required">
                        <el-form-item prop="contractEndTime">
                            <el-date-picker align="right" type="datetime" :style="{ width: '100%' }"
                                placeholder="请输入合同签订时间" v-model="formData.contractEndTime" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" :disabled="isEdit">
                            </el-date-picker>
                        </el-form-item>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同金额" labelClassName="required">
                        <el-form-item prop="contractMoney">
                            <el-input placeholder="请输入合同金额" :disabled="isEdit" v-model="formData.contractMoney">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="是否含税" labelClassName="required">
                        <el-form-item prop="tax">
                            <el-radio-group v-model="formData.tax" :disabled="isEdit">
                                <el-radio label="0">含税</el-radio>
                                <el-radio label="1">不含税</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="税点" labelClassName="required">
                        <el-form-item prop="taxPoint">
                            <el-input placeholder="请输入税点" :disabled="isEdit" type="number" v-model="formData.taxPoint"
                                min=“0.00” :min="0" step=“0.01”>
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同附件">
                        <el-upload ref="uploadContractFile" list-type="picture-card" :action="action"
                            :file-list="fileList" :data="fileParams" :auto-upload="false" :on-change="uploadOnchange"
                            multiple accept='.pdf' class='el-contract-upload'>

                            <i slot="default" class="el-icon-plus"></i>

                            <div slot="file" slot-scope="{file}" class="file-list">

                                <div class="avator"><i class="el-icon-document"></i></div>
                                <div class="file-content" :title="file.name">{{ file.name }}</div>
                                <div class="file-operate">
                                    <span class="" v-if="isEdit" @click="handleDownload(file)">
                                        <i class="el-icon-download"></i>
                                    </span>
                                    &nbsp;
                                    <span class="" @click="handleRemove(file)">
                                        <i class="el-icon-delete"></i>
                                    </span>
                                </div>
                            </div>
                            <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传pdf文件，且不超过500kb</div> -->
                        </el-upload>
                    </el-descriptions-item>

                </el-descriptions>
                <div class="cell-border" :style="{ borderBottom: 0 }">
                    签订信息
                </div>
                <el-descriptions :column="3" border class="contract-description-form">
                    <el-descriptions-item label="乙方签订人" labelClassName="required">
                        <el-form-item prop="partybName">
                            <el-input placeholder="请输入乙方签订人" :disabled="isEdit" v-model="formData.partybName">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同签订时间" labelClassName="required">
                        <el-form-item prop="signingTime">
                            <el-date-picker v-model="formData.signingTime" align="right" type="datetime"
                                placeholder="请输入合同签订时间" :disabled="isEdit" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同制定人" labelClassName="required">
                        <el-form-item prop="preparedBy">
                            <el-input placeholder="请输入合同制定人" :disabled="isEdit" v-model="formData.preparedBy">
                            </el-input>
                        </el-form-item>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同保管人" labelClassName="required">
                        <el-form-item prop="safekeeping">
                            <el-input placeholder="请输入合同保管人" v-model="formData.safekeeping"></el-input>
                        </el-form-item>
                    </el-descriptions-item>
                </el-descriptions>
                <div class="cell-border">
                    备注
                </div>
                <div class="cell-border">
                    <el-form-item prop="contarctRemarks">
                        <el-input type="textarea" v-model="formData.contarctRemarks"></el-input>
                    </el-form-item>
                </div>
                <br />
                <el-form-item>
                    <el-button type="primary" @click="dialogVisible = true">{{ !isEdit ? '创建合同' : '修改合同' }}</el-button>
                    <el-button @click="$store.dispatch('tagsView/delView', $route); $router.back();">返回</el-button>
                    <!-- <el-button @click="closeDrawer">取消</el-button> -->
                </el-form-item>
            </el-form>
        </div>
        <el-dialog :title="isEdit ? '确认修改' : '确认提交'" :visible.sync="dialogVisible" width="30%">
            <span>确定{{ isEdit ? '修改' : '添加' }}合同</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addContract">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { selectAllContractTypeList, selectAllContractList, addContract, getContractById, updateContract, selectContractFiles, deleteContract } from '@/api/contract'
import { deepClone } from '@/utils'
import { contractNatures, addFormValidRules } from '../contractStaticData'
import { mapGetters } from 'vuex'
import { previewPDF } from '@/utils/download'
import  axios from 'axios'
// import { checkPhone } from '@/utils/myValidate'
export default {
    // props: ['drawerVisible'],
    data() {
        return {
            // checkedContractNature: this.$route.query.contractNature,
            formData: {
                firstParty: '',
                contractName: '',
                contractNature: this.$route.query.checkedContractNature,
                contarctRemarks: ' ',
                contractStartTime: '',
                contractFirstParty: '',
                contractMoney: '',
                contractNumber: '',
                contractPaetyb: '',
                contractEndTime: '',
                signingTime: '',
                partybName: '',
                taxPoint: '',
                tax: '0',
                typeId: '',
                safekeeping: '',
                firstPartyAddress: '',
                preparedBy: '',
                firstPartyPhone: '',
                contractParent: ''
            },
            fileList: [],
            fileParams: {},
            contractTypeList: [],
            contractParentList: [],
            contractNatures: deepClone(contractNatures),
            isEdit: false,
            addFormValidRules,
            action: '',
            dialogVisible: false,
            deleteFiles: []
        }
    },
    computed: {
        ...mapGetters([
            'companyId'
        ])
    },
    watch: {
        '$route.query.checkedContractNature': function () {
            this.$route.query.checkedContractNature && (this.formData.contractNature = this.$route.query.checkedContractNature);
        }
    },
    created() {
        this.action = process.env.VUE_APP_BASE_API + '/file/updataContractDocuments'
    },
    mounted() {
        const { contractId } = this.$route.query
        this.getContractTypeList()  //获取合同类型

        // 编辑
        if (this.$route.path.indexOf('/editContract') >= 0 && contractId) {
            this.isEdit = true;
            this.getContractDetail(contractId)
            this.getContractFiles(contractId)  //获取合同文件
            // 添加
        } else if (this.$route.path.indexOf('/addContract') >= 0 && this.$route.query.checkedContractNature !== undefined) {
            this.isEdit = false;
            if (this.$route.query.checkedContractNature.toString() === '2') {
                this.getParentContractList() //获取母合同列表
            }
        } else {
            this.$router.back()
        }
    },
    methods: {
        // closeDrawer() {
        //     this.$emit('closeDrawer')
        // },
        getParentContractList() {
            const params = {
                companyId: this.companyId || this.$store.getters.companyId
            }
            selectAllContractList(params).then(res => {
                if (res.success) {
                    // console.log(res.data)
                    this.contractParentList = res.data
                } else {
                    this.$message.warning("获取合同类型失败")
                }
            })
        },
        addContract() {
            // let validRes = this.validFormData()
            // if (validRes.length) {
            //     this.$message.warning("带 * 号必填，请正确填写信息")
            //     return
            // }

            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.formData.contractStartTime > this.formData.contractEndTime) {
                        this.dialogVisible = false
                        this.$message.warning('合同开始时间和结束时间不符合实际')
                        return
                    }
                    const params = {
                        companyId: this.companyId || this.$store.getters.companyId,
                        ...this.formData
                    }
                    // const toNumberKeys = ['contractNature','contractParent','contractMoney']
                    // toNumberKeys.forEach(key => {
                    //     params[key] = Number(params[key])
                    // })
                    !this.formData.contarctRemarks && (params.contarctRemarks = ' ')
                    if (!this.isEdit) {
                        addContract(params).then(res => {
                            if (res.success) {
                                this.$message.success("成功添加合同")
                                this.updateContractFile(res.data)
                                setTimeout(() => {
                                    this.$store.dispatch("tagsView/delView", this.$route);
                                    this.$router.push({ path: '/contractList' })
                                }, 1000);
                            } else {
                                this.$message.warning("添加合同失败：" + res.msg)
                            }
                        })
                    } else {
                        updateContract(params).then(res => {
                            if (res.success) {
                                this.updateContractFile(this.formData.contractId)
                                this.$message.success("成功修改合同")
                                setTimeout(() => {
                                    this.$store.dispatch("tagsView/delView", this.$route);
                                    this.$router.push({ path: '/contractList' })
                                }, 1000);
                            } else {
                                this.$message.warning("添加修改失败：" + res.msg)
                            }
                        })
                    }
                } else {
                    this.dialogVisible = false
                }
            });
        },
        updateContractFile(contractId) {
            this.fileParams.Id = String(contractId)
            this.fileParams.companyId = this.companyId
            this.$refs.uploadContractFile.submit()
            if (this.deleteFiles.length) {
                this.deleteFiles.forEach(file => {
                    if(file.id){
                        deleteContract(file)
                    }
                })
                // axios.all(httpArr)
            }
        },
        getContractTypeList() {
            const params = {
                state: 0,
                companyId: this.companyId || this.$store.getters.companyId
            }
            selectAllContractTypeList(params).then(res => {
                if (res.success) {
                    // console.log(res.data)
                    this.contractTypeList = res.data
                } else {
                    this.$message.warning("获取合同类型失败")
                }
            })
        },
        getContractDetail(contractId) {
            if (contractId) {
                const params = {
                    contractId
                }
                getContractById(params).then(res => {
                    if (res.success) {
                        // console.log(res.data)
                        if (res.data.contractNature.toString() === '2') {
                            this.getParentContractList()
                        }
                        this.formData = res.data
                    } else {
                        this.$message.warning("获取合同失败")
                    }
                })
                // get()
            }
        },
        getContractFiles(contractId) {
            const params = {
                contractId
            }
            selectContractFiles(params).then(res => {
                if (res.success) {
                    this.fileList = res.data.map(item => {
                        item.name = item.filePath.slice(item.filePath.lastIndexOf('/') + 1, item.filePath.length)
                        return item
                    })
                } else {
                    this.fileList = []
                }
            })
        },

        uploadOnchange(file, fileList) {
            const index = this.fileList.findIndex(item => item.uid === file.uid)
            if (index >= 0) {
                this.fileList.splice(index, 1)
            } else {
                this.fileList.push(file)
            }
        },
        handleDownload(file) {
            let { filePath } = file
            // let url = process.env.VUE_APP_BASE_API + filePath;
            previewPDF(filePath)
        },
        
        handleRemove(file) {
            const index = this.fileList.findIndex(item => item.uid === file.uid)
            if (index >= 0) {
                const deleteFile = this.fileList.splice(index, 1)
                if (deleteFile.length) {
                    this.deleteFiles.push(deleteFile[0])
                }
            }
            // splice(index,len,[item])
            // deleteContract(file).then(res => {
            //     if (res.success) {
            //         this.$message.success("成功删除合同文件")
            //         this.getContractFiles(file.contractId)
            //     } else {
            //         this.$message.warning("删除合同文件失败")
            //     }
            // })
        },
        validFormData() {
            let requiredParams = deepClone(this.formData);
            delete requiredParams.contractParentName
            let result = []
            delete requiredParams.contarctRemarks
            if (!this.$route.query.checkedContractNature || this.$route.query.checkedContractNature.toString() !== '2') {
                delete requiredParams.contractParent //非母合同
            }
            for (const key in requiredParams) {
                if (!requiredParams[key] && requiredParams[key] !== 0) {
                    result.push(key)
                }
                // else if(key === '' && !checkPhone(requiredParams[key])){

                // }
            }
            return result
        }
    }
}
</script>
<style rel="stylesheet/scss" scoped lang="scss">
.header {
    padding: 25px 15px;

    i {
        float: right;
        color: gray;
        cursor: pointer;
    }
}

.container {
    padding: 0 15px;

    .cell-border {
        border: 1px solid #e6ebf5;
        border-top: 0;
        // border-bottom: 0;
        padding: 12px 10px;
        font-weight: 600;
        font-size: 14px;
    }

}

.file-list {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 250px;
    padding: 0 5px;

    .avator {
        width: 10%;
        font-size: 32px;
        color: #d75b5b;
    }

    .file-content {
        width: 80%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-left: 10px;
    }

    .file-operate {
        width: 15%;
        font-size: 16px;
        display: flex;
        justify-content: space-around;
        align-items: center;

        span {
            cursor: pointer;
        }

    }

}
</style>