<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>
                <el-descriptions :column="3" border class="contract-description-form">
                    <el-descriptions-item label="母合同名称" :span="3" v-if="parseInt(formData.contractNature) === 2">
                        <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.name"></el-option>
                        </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同名称" :span="2" labelClassName="required"
                        content-class-name="my-content">
                        <el-input placeholder="请输入合同名称" v-model="formData.contractName"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同性质" labelClassName="required">
                        {{ contractNatures[formData.contractNature] }}
                    </el-descriptions-item>
                    <el-descriptions-item label="合同乙方" labelClassName="required">
                        <el-input placeholder="请输入合同名称合同乙方" v-model="formData.contractPaetyb"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同编号" labelClassName="required">
                        <el-input placeholder="请输入合同编号" v-model="formData.contractNumber"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同类型" labelClassName="required">
                        <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-descriptions-item>

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

                    <el-descriptions-item label="客户联系地址" labelClassName="required">
                        <el-input placeholder="请输入客户联系地址" v-model="formData.firstPartyAddress"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同开始日期" labelClassName="required">
                        <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">
                        </el-date-picker>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同结束日期" labelClassName="required">
                        <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">
                        </el-date-picker>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同金额" labelClassName="required">
                        <el-input placeholder="请输入合同金额" type="number" v-model="formData.contractMoney" step=“0.01”>
                        </el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="是否含税" labelClassName="required">
                        <el-radio-group v-model="formData.tax">
                            <el-radio label="0">含税</el-radio>
                            <el-radio label="1">不含税</el-radio>
                        </el-radio-group>
                    </el-descriptions-item>
                    <el-descriptions-item label="税点" labelClassName="required">
                        <el-input placeholder="请输入税点" type="number" v-model="formData.taxPoint" min=“0.00” step=“0.01”>
                        </el-input>
                    </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="" @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-input placeholder="请输入乙方签订人" v-model="formData.partybName"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同签订时间" labelClassName="required">
                        <el-date-picker v-model="formData.signingTime" align="right" type="datetime"
                            placeholder="请输入合同签订时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-descriptions-item>

                    <el-descriptions-item label="合同制定人" labelClassName="required">
                        <el-input placeholder="请输入合同制定人" v-model="formData.preparedBy"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="合同保管人" labelClassName="required">
                        <el-input placeholder="请输入合同保管人" v-model="formData.safekeeping"></el-input>
                    </el-descriptions-item>
                </el-descriptions>
                <div class="cell-border">
                    备注
                </div>
                <div class="cell-border">
                    <el-input type="textarea" v-model="formData.contarctRemarks"></el-input>
                </div>
                <br />
                <el-form-item>
                    <el-button type="primary" @click="addContract">{{ !isEdit ? '立即创建' : '修改' }}</el-button>
                    <!-- <el-button @click="closeDrawer">取消</el-button> -->
                </el-form-item>
            </el-form>
        </div>
        <!-- </el-drawer> -->
    </div>
</template>
<script>
import { selectAllContractTypeList, selectAllContractList, addContract, getContractById, updateContract, selectContractFiles, deleteContract } from '@/api/contract'
import { deepClone } from '@/utils'
import { contractNatures } from '../contractStaticData'
import { mapGetters } from 'vuex'
import { downloadPDFFile } from '@/utils/download'
export default {
    // props: ['drawerVisible'],
    data() {
        return {
            // checkedContractNature: this.$route.query.contractNature,
            formData: {
                firstParty: '',
                contractName: '',
                contractNature: this.$route.query.checkedContractNature,
                contarctRemarks: ' ',
                contractStartTime: '',
                contractFirstParty: '',
                contractMoney: "0",
                contractNumber: '',
                contractPaetyb: '',
                contractEndTime: '',
                signingTime: '',
                partybName: '',
                taxPoint: '',
                tax: '0',
                typeId: '',
                safekeeping: '',
                firstPartyAddress: '',
                preparedBy: '',
                firstPartyPhone: '',
                contractParent: ''
            },
            fileList: [],
            fileParams: {},
            contractTypeList: [],
            contractParentList: [],
            contractNatures: deepClone(contractNatures),
            isEdit: false,
            action: '',
            uploadChange: false
        }
    },
    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
            }
            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.addContractFile(res.data)
                        setTimeout(() => {
                            this.$router.push({path: '/contractList'})
                        }, 1000);
                    } else {
                        this.$message.warning("添加合同失败")
                    }
                })
            } else {
                this.addContractFile(this.formData.contractId)
                updateContract(params).then(res => {
                    if (res.success) {
                        this.$message.success("成功修改合同")
                        setTimeout(() => {
                            this.$router.push({path: '/contractList'})
                        }, 1000);
                    } else {
                        this.$message.warning("添加修改失败")
                    }
                })
            }

        },
        uploadOnchange(file, fileList) {
            this.uploadChange = true
        },
        addContractFile(contractId) {
            this.fileParams.Id = String(contractId)
            this.uploadChange && this.$refs.uploadContractFile.submit()
        },
        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 = []
                }
            })
        },
        handleDownload(file) {
            let {name, filePath} = file
            let url = process.env.VUE_APP_BASE_API + filePath;
            downloadPDFFile(url, name)
        },
        handleRemove(file) {
            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)
                }
            }
            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>