<template>
	<el-dialog
	 :close-on-click-modal="false"
	 :close-on-press-escape="false"
	 :title="dialogTitle"
	 :visible.sync="dialogVisible"
	 top="50px"
	 width="75%"
	 :before-close="beforeClose"
	>
		<div class="tabsdom">
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="报支申请" name="first">

					<el-form
					 ref="elformData"
					 :model="form"
					 :rules="rules"
					 class="cost_form"
					 label-width="125px"
					 style="width: 100%;padding: 5px"
					>

						<el-card shadow="always" style="padding: 15px 5px 5px 15px">
							<el-row :gutter="10">
								<el-col :span="24">
									<el-form-item label="关联项目" prop="proId">
										<el-select v-model="form.proId" filterable placeholder="关联项目名称" @change="projectChange">
											<el-option
											 v-for="item in ProjectData"
											 :key="item.value"
											 :label="item.label"
											 :value="item.value"
											>
												<span style="float: left">{{ item.label }}</span>
												<span style="float: right; color: #8492a6; font-size: 13px">{{
														item.custname
													}}</span>
											</el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>


							<el-card class="pdtopbottom16 mb25 pdtop16px">
              <span class="moneydetails">
<!--                  <span style="color: red">*</span>-->
                  费用明细
              </span>
								<el-row :gutter="10" class="eltype">
									<el-col :span="4" class="col-txt txtc"><span>费用&成本类型</span></el-col>
									<el-col :span="4" class="col-txt txtc">
										金额（元）
									</el-col>
									<el-col :span="4" class="col-txt txtc">
										发票号
									</el-col>
									<el-col :span="10" class="col-txt txtc">
										单据
									</el-col>
								</el-row>
								<el-row
								 v-for="(item,index) in form.applyUseMoneyDetailListString"
								 :gutter="10"
								 class="eltype"
								>
                                    <el-col :span="5">
                                        <el-select
                                            size="small"
                                            v-model="item.feeType"
                                            filterable
                                            placeholder="请选择"
                                            style="width: 100%"
                                        >
                                            <el-option
                                                v-for="item in cbFyTypes"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-col>
									<el-col :span="4">
										<el-input-number
										 v-model="item.feeMoney"
										 :controls="false"
										 size="small"
										 controls-position="right"
										 placeholder="请填写金额，如0.1"
										 style="width: 100%"
										/>
									</el-col>
									<el-col :span="4">

										<el-input
										 v-model="item.fileNumber"
										 :controls="false"
										 size="small"
										 :disabled="item.fileList==0"
										 controls-position="right"
										 placeholder="请输入发票号(需上传发票)"
										 style="width: 100%"
										/>

									</el-col>
									<el-col :span="10" class="col-input">
										<!--                    {{ item.fileList }}-->
										<el-upload
										 :action="$constant.BASE_URI+'/FileController/upload'"
										 :file-list="item.fileList"
										 :http-request="(params)=>{uploadFile(params,index)}"
										 :limit="5"
										 :multiple="false"
										 :show-file-list="false"
										 class="upload-demo"
										 style="width: 30%;float: left;margin-left: 42px"
										>
											<el-button size="small" style="font-size: 14px" type="text">
												上传发票
												<img
												 src="./fapiaoicon.png"
												 style="margin-left: 5px;position: absolute;top: 13.5px;"
												 width="24px"
												/>

											</el-button>
										</el-upload>
										<el-radio-group
										 v-model="item.fileType"
										 style="margin-left: 30px;"
										 @input="changeFileType($event,index)"
										>
											<el-radio v-if="false" :label="1">上传发票</el-radio>
											<el-radio :label="2">发票后补</el-radio>
											<el-radio :label="3">无发票</el-radio>
										</el-radio-group>

									</el-col>
									<el-col :span="1" class="col-txt txtc">
										&nbsp;
										<el-button
										 v-if="index!=0"
										 circle
										 icon="el-icon-minus"
										 @click="deleteRow(index)"
										/>
									</el-col>
									<el-col :span="1" class="col-txt txtc">
										<el-button
										 v-if="index==form.applyUseMoneyDetailListString.length-1"
										 circle
										 icon="el-icon-plus"
										 type="primary"
										 @click="addListRow()"
										/>
									</el-col>
									<el-col :span="13">&nbsp;</el-col>
									<el-col :span="11">
										<div v-for="(file,i) in item.fileList" v-if="item.fileList.length>0"
												 style="margin: 0 0px 0px 45px;"
										>
											<div>
												<a :href="file.url">{{ file.name }}</a>
												<span class="el-upload-list__item-actions">
											 <i class="el-icon-delete" @click="handlePictureRemove(i,file,item.fileList)"/>
									   	 </span>
											</div>

										</div>

									</el-col>
								</el-row>
								<div class="feeMoneyTotal">
									<div style="float: right">共计金额（元）：{{ feeMoneyTotal() }}</div>
								</div>
							</el-card>

							<el-row :gutter="10">
								<el-col :span="24">
									<el-form-item label="用途" prop="useReasons">
										<el-input v-model="form.useReasons" type="textarea"/>
									</el-form-item>
								</el-col>


								<el-col :span="24">
									<el-form-item label="收款单位（人）" prop="payeeName">
										<el-input v-model="form.payeeName"></el-input>
									</el-form-item>
								</el-col>


								<el-col :span="12">
									<el-form-item label="开户银行">
										<el-input v-model="form.bankName"></el-input>
									</el-form-item>
								</el-col>

								<el-col :span="12">
									<el-form-item label="银行账户" label-width="125px">
										<el-input v-model="form.bankAccountNum" filterable placeholder="请输入银行账户"/>
									</el-form-item>
								</el-col>

								<el-col :span="24">
									<el-form-item label="抄送">
										<user-select
										 :default-select="selectList"
										 :multiple="true"
										 class="cclist"
										 @selectValue="parentMethod"
										/>
									</el-form-item>
								</el-col>

							</el-row>
						</el-card>

					</el-form>
				</el-tab-pane>
				<el-tab-pane label="流程图  " name="second">
					<costCanvas ref="costCanvas"/>
				</el-tab-pane>
			</el-tabs>
		</div>
		<div slot="footer">
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button :loading="loading" type="primary" @click="confirmSubmit()">确 定</el-button>
		</div>
	</el-dialog>

</template>

<script>
import { upload } from '@/static/utils/channel'
import Base from '@/views/base/base'
import BaseData from '@/views/base/baseData'
import UserSelect from '@/views/components/UserSelect'
import costCanvas from '@/views/workflow/components/myProcess/costCanvas.vue'

export default {
	name: 'ApplyPay',
	mixins: [Base, BaseData],
	components: {
		upload, UserSelect, costCanvas
	},
	data() {
		return {
			row: {},
			rules: {
				proId: [{ required: true, message: '请选择关联项目', trigger: 'change' }],
				useReasons: [{ required: true, message: '请输入费用报支用途', trigger: 'blur' }],
				payeeName: [{ required: true, message: '请输入收款单位（人）', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
			},
			selectList: [],
			loading: false,
			dc_key: ['ORDER_STATUS', 'PAY_TYPE', 'BUDGET_FY'],

			ProjectData: [],
			dialogTitle: '费用报支申请-重新发起',
			dialogVisible: false,
			form: {
				applyUseMoneyDetailListString: [{ fileList: [], fileType: 1 }]
			},
			activeName: 'first',
            cbFyTypes:[]
		}
	},
	mounted() {
		this.initDict(this.dc_key).then((res) => {

			this.initProject({ /* signstatus: '2,3'*/ })

		})
	},
	methods: {
		handleClick(tab, event) {
			this.canVasStatus = false
			if (this.activeName == 'second') {
				this.canVasStatus = true
				this.$nextTick(() => {
					this.$refs.costCanvas.createNodeCanvas(this.row)

				})
			}
		},
		beforeClose() {
			this.form = {
				applyUseMoneyDetailListString: []
			}
			this.dialogVisible = false
			this.activeName = 'first'
			this.$forceUpdate()
		},
		feeMoneyTotal() {
			let feeMoneyTotal = 0
			for (let i = 0; i < this.form.applyUseMoneyDetailListString.length; i++) {
				feeMoneyTotal += this.form.applyUseMoneyDetailListString[i].feeMoney
			}
			this.form.feeMoneyTotal = feeMoneyTotal
			return feeMoneyTotal.toFixed(2)
		},
		changeFileType(e, i) {
			if (e != 1) {
				this.form.applyUseMoneyDetailListString[i].fileList = []
			}
			this.$forceUpdate()
		},
		parentMethod(val) {
			if (val.length > 0) {
				this.form.ccList = val.join(',')
			}
		},

		handlePictureRemove(i, file, fileList) {
			fileList.splice(i, 1)

			let copyFileList = [...fileList]
			fileList = copyFileList

			this.form.applyUseMoneyDetailListString = this.form.applyUseMoneyDetailListString.map((e) => {
				return e
			})
		},
		uploadFile(params, i) {
			upload(params, true).then((res) => {
				this.form.applyUseMoneyDetailListString[i].fileList.push(res)
				this.form.applyUseMoneyDetailListString[i].fileType = 1
				this.$message.success('上传成功')
				this.$forceUpdate()
			})

		},
        async projectChange(){
            this.cbFyTypes=[]
            let submitData = {proId:this.form.proId }
            const { data } = await this.baseRequest1('ProMainDashboardController', 'getRightBudgetList', submitData)

            if (data) {
                const fyList = data.fyList || []
                const cbList = data.cbList || []
                fyList.forEach(item=>{
                    const i = {
                        value : item.budgetChildType,
                        label:item.budgetType+'-'+item.budgetChildType
                    }
                    this.cbFyTypes.push(i)
                })
                cbList.forEach(item=>{
                    const i = {
                        value : item.budgetChildType,
                        label:item.budgetType+'-'+item.budgetChildType
                    }
                    this.cbFyTypes.push(i)
                })
            }
        },
		baseRequest1(prefix, opUrl, postData) {
			return this.$channel.globleRequest(prefix, opUrl, postData, 'project task')
		},
		async confirmSubmit() {

			for (let i = 0; i < this.form.applyUseMoneyDetailListString.length; i++) {
				if (this.form.applyUseMoneyDetailListString[i].fileType == 1
				 &&
				 (!this.form.applyUseMoneyDetailListString[i].fileList
					||
					this.form.applyUseMoneyDetailListString[i].fileList.length == 0)) {
					this.$message.warning(`请上传费用明细中第${i + 1}行的发票文件`)
					return
				}
				if (this.form.applyUseMoneyDetailListString[i].fileType == 1 && this.form.applyUseMoneyDetailListString[i].fileNumber.length == 0) {
					this.$message.warning(`请检查费用明细中第${i + 1}行，并输入发票号`)
					return
				}
			}
			this.$refs.elformData.validate(async(valid) => {
				if (valid) {
					let formData = { ...this.form }
					formData.applyUseMoneyDetailListString.forEach((e) => {
						if (e.fileList) {
							e.fileDataIds = e.fileList.map((e) => {
								return e.data
							}).join()
						}

					})
					let params = formData.applyUseMoneyDetailListString.map((e) => {
						return {
							fileType: e.fileType,
							fileDataIds: e.fileDataIds,
							feeMoney: e.feeMoney,
							feeType: e.feeType,
							fileNumber: e.fileNumber
						}
					})
					let submitData = { ...formData, applyUseMoneyDetailListString: JSON.stringify(params) }
					this.loading = true
					const { data } = await this.baseRequest1('ApplyUseMoneyController', 'addApplyUseMoneyAgain', submitData)
					this.loading = false
					if (data.code == 200) {

						this.form = { applyUseMoneyDetailListString: [{ fileType: 1, fileList: [] }] }
						this.dialogVisible = false
						this.$refs.elformData.clearValidate()
						this.$message.success('流程发起成功')
						this.$emit('getData')
					}
				}
			})
		},
		async setVisible(status, row) {
			this.row = row
			this.activeName = 'first'
			const { data } = await this.baseRequest1('ApplyUseMoneyController', 'getInfoByFlowMainId', { flowMainId: row.id })

			this.form = data
			this.form.applyUseMoneyDetailListString = data.applyUseMoneyDetailList
			for (const e of this.form.applyUseMoneyDetailListString) {
				if (e.fileDataIds.length > 0) {

					// e.fileList = e.fileDataIds.split(',')
					const { data: fileTaoTaoList } = await this.baseRequest1('FileZtController', 'findFileInfoByIds/' + e.fileDataIds, '')
					e.fileList = fileTaoTaoList.data.map((file) => {
						return {
							url: this.$constant.BASE_URI + '/FileController/download/' + file.id,
							name: file.fileName,
							data: file.id,
							uid: new Date().getTime()
						}
					})
				} else {
					e.fileList = []
				}
			}

			// $constant.BASE_URI+'/FileController/download/'
			this.selectList = data.flowMainCcList.map((e) => {
				return e.ccUser
			})
			console.log(this.selectList)
			this.dialogVisible = status
            this.projectChange()
			this.row = row
			delete this.form.flowMainCcList
			delete this.form.applyUseMoneyDetailList
		},
		addListRow() {
			const _this = this
			_this.form.applyUseMoneyDetailListString.push({
				feeType: this.dc_data.BUDGET_FY[0].value,
				fileList: [],
				fileType: 1,
				feeMoney: 0,
				fileNumber: ''
			})
		},
		deleteRow(index) {
			this.form.applyUseMoneyDetailListString.splice(index, 1)
		}
	}
}
</script>

<style lang="scss">
.cclist {
	.col-input {
		padding: 0;
	}
}

.mb25 {
	margin-bottom: 25px;
}

.pdtopbottom16 {
	padding: 0px 16px;
}

.pdtop16px {
	padding-top: 16px;
}

.cost_form {
	.col-input {
		font-weight: 400;
	}

	.el-form-item__label .moneydetails {
		text-align: right;
		font-size: 16px;
		font-family: 微软雅黑;
		padding-right: 10px;
		line-height: 40px;
		word-break: keep-all;
		white-space: nowrap;
		color: #606266;
		text-rendering: optimizeLegibility;
		font-weight: 400;
	}

	.moneydetails {
		text-align: right;
		font-size: 16px;
		font-family: 微软雅黑;
		padding-right: 10px;
		word-break: keep-all;
		white-space: nowrap;
		color: #606266;
		text-rendering: optimizeLegibility;
		font-weight: 400;


	}

	.moneydetails:before {
		content: "*";
		color: #ff4949;

	}
}


.txtc {
	text-align: center
}

.ml5 {
	margin-left: 5px;
}

.eltype {
	margin-bottom: 5px;
}

.tabsdom {
	.el-tabs__header {
		text-align: center !important;
		width: 139px !important;
		text-align: center !important;
		display: block !important;
		margin: auto !important;
		margin-bottom: 15px !important;
	}

	.el-tabs__nav-wrap::after {
		display: none;
	}

	.el-upload {
		width: 100%;
	}
}

.feeMoneyTotal {
	width: 100%;
	height: 14px;
	font-size: 14px;
	font-weight: 400;
	color: #1890FF;
	margin-top: 31px;
	margin-bottom: 13px;
}
</style>
