<template>
  <div class="contractAdd">
    <el-form ref="form" :model="form" style="width: 100%;padding: 5px" :rules="rules">
      <el-row>
        <el-col style="padding-bottom: 10px">
          <el-card shadow="always" style="padding: 15px 5px 5px 15px">
            <el-row>
              <el-col :span="5" class="col-txt"><span>网签备案号</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.recordNumber" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>合同编号</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.contractNumber" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>出卖人</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input value="无锡市安居投资发展有限公司" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in form.dynamicItem" :key="index">
              <el-col :span="5 " class="col-txt"><span>购房人{{ index + 1 }}</span></el-col>
              <el-col :span="4" class="col-input">
                <el-form-item :prop="'dynamicItem.' + index + '.name'">
                  <el-input
                    v-model="item.name"
                    placeholder="请填写姓名"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4" class="col-input">
                <el-form-item :prop="'dynamicItem.' + index + '.identityCard'">
                  <el-input
                    v-model="item.identityCard"
                    placeholder="请填写身份证号"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4" class="col-input">
                <el-form-item :prop="'dynamicItem.' + index + '.phone'">
                  <el-input
                    v-model="item.phone"
                    placeholder="请填写手机号"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="index !== 0" :span="6" class="col-input">
                <el-form-item :prop="'dynamicItem.' + index + '.relationship'">
                  <el-select
                    v-model="item.relationship"
                    placeholder="与1的关系"
                    filterable

                    disabled
                  >
                    <el-option
                      v-for="relationship in dc_data.RELATIONSHIP"
                      :key="relationship.value"
                      :label="relationship.label"
                      :value="relationship.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>房屋</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-cascader
                    v-model="form.houseId"
                    :append-to-body="false"
                    style="width: 100%;"
                    :options="TreeData"
                    disabled
                    @change="houseChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span><span class="red-asterisk">*</span>实测建筑面积（㎡）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item prop="actualBuildArea">
                  <el-input v-model="form.actualBuildArea" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>套内建筑面积（㎡）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.actualInternalArea" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>分摊共有建筑（㎡）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.actualShareArea" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>房产测绘机构</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-select
                    v-model="form.institution"

                    placeholder=""
                    filterable
                    :disabled="isView"
                  >
                    <el-option
                      v-for="item in dc_data.MAPPING_INSTITUTION"
                      :key="item.value"

                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>签约日期</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-date-picker
                    v-model="form.signingDate"

                    type="date"
                    placeholder="年月日"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>备注说明</span></el-col>
              <el-col :span="18" class="col-input">
                <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 100}" maxlength="2000" show-word-limit />
              </el-col>
            </el-row>
            <el-row>
              <el-divider />
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span style="font-weight: bold;font-size: large">房价款</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>房屋买卖单价（元/㎡）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.housePrice" readonly placeholder="请先录入总价款,系统会自动计算出房屋买卖单价" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span><span class="red-asterisk">*</span>总价款（元）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item prop="totalPrice">
                  <el-input v-model="form.totalPrice" @input="totalPriceChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>买受人产权份额占比为（%）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.buyerProportion" type="number" @input="proportionChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>买受人出资金额（元）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.buyerMoney" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>付款方式</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-select
                    v-model="form.paymentMethod"
                    placeholder="请选择"
                    :disabled="isView"
                  >
                    <el-option
                      v-for="item in dc_data.PAYMENT_METHODS"
                      :key="item.value"

                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.paymentMethod == '2'">
              <el-col :span="5" class="col-txt"><span>首付比例</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-select
                    v-model="form.downPaymentsProportion"
                    placeholder="请选择"
                    size="small"
                    :disabled="isView"
                  >
                    <el-option
                      v-for="item in dc_data.DOWN_PAYMENT_PROPORTION"
                      :key="item.value"

                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            <el-row>-->
            <!--              <el-col :span="5" class="col-txt"><span>付款截止日</span></el-col>-->
            <!--              <el-col :span="18" class="col-input">-->
            <!--                <el-form-item>-->
            <!--                  <el-date-picker-->
            <!--                    v-model="form.deadline"-->
            <!--                    -->
            <!--                    type="date"-->
            <!--                    placeholder="年月日"-->
            <!--                    value-format="yyyy-MM-dd"-->
            <!--                  />-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--            </el-row>-->
            <el-row>
              <el-col :span="5" class="col-txt"><span>房款存入账号开户行</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-autocomplete
                    v-model="form.bankName"
                    class="inline-input"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入银行账号"
                    style="width: 100%"
                    @select="handleSelect"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>房款存入账号</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.bankNumber" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-divider />
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span style="font-weight: bold;font-size: large">专项维修资金</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>住宅专项维修资金（元/㎡）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.maintenanceFunds" @input="maintenanceFundsChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>总价款（元）</span></el-col>
              <el-col :span="18" class="col-input">
                <el-form-item>
                  <el-input v-model="form.maintenanceTotalPrice" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5" class="col-txt"><span>合同原件</span></el-col>
              <el-col :span="5" class="col-input">
                <el-form-item>
                  <el-upload
                    class="upload-demo"
                    action="/server/wx/fileController/uploadImage"
                    :http-request="uploadPhoto"
                    :before-remove="beforeRemove"
                    multiple
                    :file-list="contractOriginalList"
                    :limit="6"
                    :before-upload="$common.beforeUploadJustWordExcel"
                  >
                    <el-button v-if="!isView" size="small" type="primary">点击上传</el-button>
                    <div slot="file" slot-scope="{file}">
                      <a :href="file.url">{{ file.name }}</a>
                      <span v-show="!isView" class="el-upload-list__item-actions">
                        <i class="el-icon-delete" @click="handlePictureRemove(file,contractOriginalList)" />
                      </span>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="5" class="col-txt"><span>其他附件</span></el-col>
              <el-col :span="5" class="col-input">
                <el-form-item>
                  <el-upload
                    class="upload-demo"
                    action="/server/wx/fileController/uploadImage"
                    :http-request="uploadContractOther"
                    :before-remove="beforeRemove"
                    multiple
                    :file-list="contractOtherList"
                    :limit="6"
                    :before-upload="$common.beforeUploadJustWordExcel"
                  >
                    <el-button v-if="!isView" size="small" type="primary">点击上传</el-button>
                    <div slot="file" slot-scope="{file}">
                      <a :href="file.url">{{ file.name }}</a>
                      <span v-show="!isView" class="el-upload-list__item-actions">
                        <i class="el-icon-delete" @click="handlePictureRemove(file,contractOtherList)" />
                      </span>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: right">
      <el-button @click="cancel()">关 闭</el-button>
      <el-button v-if="!isView" type="primary" @click="confirmSubmit()">暂 存</el-button>
      <el-button v-if="!isView" type="primary" @click="confirmSubmit('signing')">签 约</el-button>
    </div>
  </div>
</template>
<script>
import Base from '@/views/base/base'
import BaseData from '@/views/base/baseData'
import { upload } from '@/static/utils/channel'

export default {
    name: 'ContractManage',
    components: {
    },
    mixins: [Base, BaseData],
    props: {
        // 确认从哪个页面跳转过来的,这样可以做相应的操作
        fromAddress: {
            type: String,
            default: ''
        },
        signYear: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            dc_key: ['CONTRACT_STATUS', 'MAPPING_INSTITUTION', 'PAYMENT_METHODS', 'DOWN_PAYMENT_PROPORTION', 'RELATIONSHIP'],
            // 弹框相关
            dialogVisible: false,
            dialogTitle: '新增',
            form: {
                downPaymentsProportion: '',
                paymentMethod: '',
                institution: '',
                dynamicItem: [
                    {
                        id: '',
                        customerManagementId: '',
                        name: '',
                        identityCard: '',
                        phone: '',
                        relationship: ''
                    }
                ]
            },
            rules: {
                // contractNumber: [{ required: true, trigger: 'blur', message: '请输入合同编号' }],
                actualBuildArea: [{ required: true, trigger: 'blur', message: '实测建筑面积' }],
                totalPrice: [{ required: true, trigger: 'blur', message: '请输入总价款' }]
            },
            contractOriginalList: [],
            contractOtherList: [],
            signingMaterialsList: [],
            contractId: '',
            TreeData: [],
            isView: false, // 查看按钮权限,
            searchTreeData: [],
            restaurants: []
        }
    },
    watch: {

    },
    mounted() {
        this.findRoomTree()
        this.initDict(this.dc_key).then((res) => {
        })
    },
    methods: {
        initData(val) {
            const _this = this
            // 查看或编辑
            if (val.id) {
                _this.isView = val.isView
                const postData = {
                    id: val.id
                }
                this.baseRequest('getById', postData).then((res) => {
                    if (res.data) {
                        const data = res.data
                        _this.form = Object.assign({}, _this.form, res.data)
                        // 合同原件
                        _this.contractOriginalList = data.contractOriginal ? JSON.parse(data.contractOriginal) : []
                        // 其他附件
                        _this.contractOtherList = data.contractOther ? JSON.parse(data.contractOther) : []
                        if (data.institution) {
                            _this.form.institution = data.institution + ''
                        }
                        if (data.paymentMethod) {
                            _this.form.paymentMethod = data.paymentMethod + ''
                        }
                        if (data.downPaymentsProportion) {
                            _this.form.downPaymentsProportion = data.downPaymentsProportion + ''
                        }
                        // 初始化专项维修资金总价款
                        const price = _this.form.maintenanceFunds
                        const area = _this.form.actualBuildArea
                        if (price && area) {
                            _this.form.maintenanceTotalPrice = price * area
                        }
                        // 初始化 买受人产权份额占比为
                        this.form.buyerProportion = 50
                    }
                }).catch(() => {
                })
                this.baseBuyerRequest('listAll', { customerManagementId: val.customerManagementId }).then(res => {
                    const data = res.data
                    _this.form.dynamicItem = data
                    this.$forceUpdate()
                })
                this.loadAll(val.id)
            }
        },
        findRoomTree: function() {
            const _this = this
            this.pubRequest('getTreeData1', '').then((res) => {
                _this.TreeData = res.data.data
            }).catch(() => {
            })
        },
        uploadPhoto: function(param) {
            upload(param, true).then((res) => {
                this.contractOriginalList.push(res)
            })
        },
        uploadContractOther: function(param) {
            upload(param, true).then((res) => {
                this.contractOtherList.push(res)
            })
        },
        confirmSubmit: function(type) {
            const _this = this
            if (!_this.form.recordNumber && !_this.form.contractNumber) {
                _this.$message.warning('网签备案号/合同编号,必须至少填写其一')
                return
            }
            const p1 = new Promise((resolve, reject) => {
                this.$refs['form'].validate((valid) => {
                    if (valid) resolve()
                })
            })

            const p2 = {}

            Promise.all([p1, p2])
                .then(() => {
                    const soaUrl = 'edit'
                    const extraData = {
                        // 合同原件
                        contractOriginal: JSON.stringify(this.contractOriginalList),
                        // 其他附件
                        contractOther: JSON.stringify(this.contractOtherList)
                    }
                    if (type === 'signing') {
                        // 合同状态
                        extraData.contractStatus = 2
                    }
                    const postData = Object.assign({}, _this.form, extraData)
                    this.baseRequest(soaUrl, postData).then(res => {
                        if (res.data.code === 200) {
                            this.$message.success('保存成功')
                            this.cancel()
                        } else {
                            this.$message.error(res.data.msg)
                        }
                    }).catch(err => {
                        this.$message.error(err)
                    })
                })
        },
        cancel() {
            this.$emit('cancel')
        },
        houseChange() {

        },
        totalPriceChange() {
            const _this = this
            const total = _this.form.totalPrice
            const area = _this.form.actualBuildArea
            if (total && area) {
                _this.form.housePrice = (total / area).toFixed(2)
            }
            // 触发买受人产权占比
            _this.proportionChange()
        },
        proportionChange() {
            const _this = this
            const total = _this.form.totalPrice
            const proportion = _this.form.buyerProportion / 100
            if (total && proportion) {
                _this.form.buyerMoney = (total * proportion).toFixed(2)
            }
        },
        maintenanceFundsChange() {
            const _this = this
            const price = _this.form.maintenanceFunds
            const area = _this.form.actualBuildArea
            if (price && area) {
                _this.form.maintenanceTotalPrice = (price * area).toFixed(2)
            }
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
            // 调用 callback 返回建议列表的数据
            cb(results)
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
            }
        },
        loadAll(data) {
            this.restaurants = []
            const postData = {
                contractId: data
            }
            this.baseRequest('getBankList', postData).then((res) => {
                const bankList = res.data
                bankList.forEach(item => {
                    const obj = {
                        value: item.bankBranchName + item.bankName,
                        label: item.bankNumber,
                        id: item.id
                    }
                    this.restaurants.push(obj)
                })
            }).catch(() => {
            })
        },
        handleSelect(item) {
            this.form.bankNumber = item.label
        },
        baseRequest(opUrl, postData) {
            return this.$channel.globeRequest('ContractManageController', opUrl, postData, 'project')
        },
        pubRequest(opUrl, postData) {
            return this.$channel.globeRequest('ParkInfoController', opUrl, postData, 'project')
        },
        baseRoomRequest(opUrl, postData) {
            return this.$channel.globeRequest('ParkRoomController', opUrl, postData, 'project')
        },
        baseBuyerRequest(opUrl, postData) {
            return this.$channel.globeRequest('BuyerController', opUrl, postData, 'project')
        }
    }
}
</script>

<style lang="scss">
.contractAdd{
    .ch-input .el-input__inner {
        border-color: #32323A;
    }
    .el-textarea__inner{
        padding-right: 75px !important;
    }
}

</style>
<style scoped>
.red-asterisk {
    color: red;
}
</style>
