<template>
  <el-dialog
    :visible.sync="showDialog"
    :title="title"
    width="90%"
    :modal-append-to-body="false"
    style="text-align:left;"
    @close="closeDialog"
    :close-on-click-modal="false"
  >
    <div class="user-panel" v-loading="loading">
      <el-form ref="form" :model="formModel" :rules="ruleValidate" :inline="true" class="demo-form-inline"  label-width="120px">
        <el-form-item label="账单名称：" prop="name">
          <el-input v-model="formModel.name" placeholder="请输入账单名称" class="input-form-main"></el-input>
        </el-form-item>
        <el-form-item label="收款方：" prop="payee">
          <el-input v-model="formModel.payee" placeholder="请输入收款方" class="input-form-main"></el-input>
        </el-form-item>
        <el-form-item label="缴费单位：" prop="companyId">
          <el-select v-model="formModel.companyId" filterable class="input-form-main" @change="handChange">
            <el-option
                v-for="company in companyList"
                :key="company.id"
                :label="company.name"
                :value="company.id"
              ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款账户：" prop="collectionAccountId">
            <el-select v-model="formModel.collectionAccountId"   class="input-form-main" >
                <el-option
                    v-for="collectionAccount in collectionAccountList"
                    :key="collectionAccount.id"
                    :label="collectionAccount.name"
                    :value="collectionAccount.id"
                ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="推送用户：" prop="personId" >
          <el-select v-model="formModel.personId" class="input-form-main" filterable>
            <el-option
                v-for="person in personList"
                :key="person.id"
                :label="person.name"
                :value="person.id"
              ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="bak">
          <el-input type="textarea" v-model="formModel.bak" placeholder="请输入备注"  class="input-form-main"></el-input>
        </el-form-item>

        <h3>账单信息</h3>
        <el-table :data="formModel.billPushGoodsList">
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="goodsId" label="收费项目">
              <template slot-scope="{row}">
                  <el-form-item>
                    <el-select v-model="row.goodsId" placeholder="请选择" style="width:150px;">
                        <el-option
                        v-for="result in goodsList"
                        :key="result.id"
                        :label="result.name"
                        :value="result.id"
                        ></el-option>
                    </el-select>
                  </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="beginEndTime" label="起止时间" width="400">
                <template slot-scope="scope">
                    <el-form-item
                    :prop="'billPushGoodsList.' + scope.$index + '.beginEndTime'"
                    :rules="ruleValidate['beginEndTime']"
                    >
                        <el-date-picker
                            v-model="scope.row.beginEndTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围"
                            value-format="yyyy-MM-dd"
                            >
                        </el-date-picker>
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="numStr" label="数量" width="120">
                <template slot-scope="scope">
                    <el-form-item
                    :prop="'billPushGoodsList.' + scope.$index + '.numStr'"
                    :rules="ruleValidate['numStr']"
                    >
                    <el-input placeholder="数量" v-model="scope.row.numStr"></el-input>
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="standard" label="收费标准">
                <template slot-scope="scope">
                    <el-form-item
                    :prop="'billPushGoodsList.' + scope.$index + '.standard'"
                    :rules="ruleValidate['standard']"
                    >
                    <el-input placeholder="收费标准" v-model="scope.row.standard"></el-input>
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="totalFee" label="合计金额" width="150">
                <template slot-scope="scope">
                    <el-form-item
                    :prop="'billPushGoodsList.' + scope.$index + '.totalFee'"
                    :rules="ruleValidate['totalFee']"
                    >
                    <el-input placeholder="合计金额" v-model="scope.row.totalFee"></el-input>
                    </el-form-item>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="200">
              <template slot-scope="{row}">
                <el-form-item>
                  <i class="el-icon-delete my-font" @click="handleDelete(row)"></i>
                  <i class="el-icon-document-add my-font" @click="handleInsert(row)"></i>
                </el-form-item>
              </template>
            </el-table-column>

            <div slot="empty">
              <el-button icon="el-icon-circle-plus-outline" :plain="true" @click="handleAdd()">新增</el-button>
            </div>
        </el-table>
      </el-form>

        <div class="el-table__empty-block" v-if="formModel.billPushGoodsList.length!=0">
          <el-button icon="el-icon-circle-plus-outline" @click="handleAdd()">新增</el-button>
        </div>

    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
    </span>
    
  </el-dialog>
</template>
<script>
import Constant from "@/constant";
import billPushApi from "@/api/business/billPush";
import companyInfoApi from "@/api/base/companyInfo";
import companyPaymentApi from "@/api/base/companyPayment";
import companyGoodsInfoApi from "@/api/base/companyGoodsInfo";
import personInfoApi from "@/api/base/personInfo";
export default {
    props: ["businessKey", "title"],
    data() {
        return {
            ruleValidate: {
                name: [{ required: true, message: "账单名称不能为空", trigger: "blur" }],
                payee: [{ required: true, message: "收款方不能为空", trigger: "blur" }],
                companyId: [{ required: true, message: "公司不能为空", trigger: "blur" }],
                collectionAccountId: [{ required: true, message: "请选择收款账户", trigger: "blur" }],
                payService: [{ required: true, message: "收费项目不能为空", trigger: "blur" }]
            },
            formModel: {
                name:"",
                payee:"",
                companyId:"",
                payService:"",
                collectionAccountId:"",
                bak:"",
                billPushGoodsList:[],
                removeBillPushGoodsList:[],
                
            },
            beginEndTime:"",
            personList:[],
            goodsList:[],
            collectionAccountList:[],
            payServiceList:[],
            tableData:[],
            companyList:[],
            showDialog: true,
            loading: false,
            submitting: false,
        }
    },
    created() {
        companyInfoApi.list().then((response)=>{
            var jsonData = response.data;
            this.companyList = jsonData.data;
        });

        companyPaymentApi.list().then((response)=>{
            var jsonData = response.data;
            this.collectionAccountList = jsonData.data;
        });
    },
    methods: {
        closeDialog() {
        this.$emit("close", false);
        },
        handChange(selVal){

            this.formModel.payService = "";

            var formData = new FormData();
            formData.append("companyId", selVal);

            companyGoodsInfoApi.findByCompanyId(formData).then((response)=>{
                var jsonData = response.data;
                this.goodsList = jsonData.data;
            });

            personInfoApi.findByCompanyId(formData).then((response)=>{
                var jsonData = response.data;
                this.personList = jsonData.data;
            });

        },
        handleSubmit() {
            var self = this;

            var billPushGoodsList = this.formModel.billPushGoodsList;

            for(var i=0;i<billPushGoodsList.length;i++){
                billPushGoodsList[i].sortNo = i+1;
                billPushGoodsList[i].beginDate = billPushGoodsList[i].beginEndTime[0];
                billPushGoodsList[i].endDate = billPushGoodsList[i].beginEndTime[1]
                billPushGoodsList[i].beginEndTime="";
            }

            var removeBillPushGoodsList = this.formModel.removeBillPushGoodsList;

            for(var j=0;j<removeBillPushGoodsList.length;j++){
                removeBillPushGoodsList[j].sortNo = j+1;
                removeBillPushGoodsList[j].beginDate = removeBillPushGoodsList[j].beginEndTime[0];
                removeBillPushGoodsList[j].endDate = removeBillPushGoodsList[j].beginEndTime[1]
                removeBillPushGoodsList[j].beginEndTime="";
            }

            this.$refs["form"].validate(valid => {
                if (valid) {
                (function() {
                    var id = self.formModel.id;
                    

                    if (id == null || id.length == 0) {
                    return billPushApi.add(self.formModel);
                    } else {
                    return billPushApi.update(self.formModel);
                    }
                })().then(function(response) {
                    var jsonData = response.data;

                    if (jsonData.result) {
                    self.$message({
                        message: "保存成功!",
                        type: "success"
                    });

                    self.$emit("close", true);
                    } else {
                    self.$message({
                        message: jsonData.message + "",
                        type: "warning"
                    });
                    self.$emit("close", false);
                    }
                });
                }
            });
        },
        handleAdd() {
            this.formModel.billPushGoodsList.push({
                sortNo: this.formModel.billPushGoodsList.length + 1,
                goodsId: "",
                beginEndTime: "",
                numStr: "",
                totalFee: "",
            });
        },
        handleInsert(row) {
            var billPushGoodsList = this.formModel.billPushGoodsList;
            var index = billPushGoodsList.indexOf(row);

            if(index>=0){
                billPushGoodsList.splice(index+1,0,{
                    sortNo: index + 2,
                    name: "",
                    beginEndTime: "",
                    numStr: "",
                    totalFee: "",
                });
            }
        },
        handleDelete(row) {
            var billPushGoodsList = this.formModel.billPushGoodsList;

            billPushGoodsList.splice(billPushGoodsList.indexOf(row), 1);

            this.formModel.removeBillPushGoodsList.push(row);
        },
    },
    mounted: function() {
        var self = this;

        (function() {
        if (self.businessKey.length == 0) {
            return billPushApi.create();
        } else {
            return billPushApi.edit(self.businessKey);
        }
        })()
        .then(response => {
            var jsonData = response.data;
            self.loading = false;

            if (jsonData.result) {

                self.formModel = jsonData.data;

                var billPushGoodsList = self.formModel.billPushGoodsList;

                for(var i=0;i<billPushGoodsList.length;i++){
                    var beginEndTime = [];
                    beginEndTime.push(billPushGoodsList[i].beginDate);
                    beginEndTime.push(billPushGoodsList[i].endDate);
                    billPushGoodsList[i].beginEndTime = beginEndTime;
                }

                if(jsonData.data.companyId!=null&&jsonData.data!=""){
                    this.handChange(jsonData.data.companyId);
                }
            } else {
                self.$message.error(jsonData.message + "");
            }
        })
        .catch(error => {
            self.$message.error(error + "");
        });
    }
}
</script>
<style>
.input-form-main{
    width: 500px;
}
.link-span{
    margin-right: 20px;
}
.my-font {
  font-size: 20px;
  cursor: pointer;
  margin-right: 10px;
}
</style>