<template>
  <div v-loading="loading" style="width: 100%;height: 100%;padding: 5px" class="AuditApply1">
    <el-form ref="auditForm" :model="auditForm" style="width: 100%;padding: 5px" :rules="auditRules">
      <el-row v-if="auditTarget == 'Project' || auditTarget === 'BudgetMaking'">
        <el-col style="padding-bottom: 10px">
          <span class="card_title">基本信息</span>
          <el-card shadow="always">
            <el-row>
              <el-col :span="3" class="col-txt"><span>项目名称</span></el-col>
              <el-col :span="8" class="col-words">
                <span>{{ auditForm.proname }}</span>
              </el-col>
              <el-col :span="4" class="col-txt"><span>项目类型</span></el-col>
              <el-col :span="8" class="col-words">
                <span>{{ auditForm.protype }}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3" class="col-txt"><span>商机状态</span></el-col>
              <el-col :span="8" class="col-words">
                <span>{{ auditForm.signStatus }}</span>
              </el-col>
              <el-col :span="4" class="col-txt"><span>预计销售金额(元)</span></el-col>
              <el-col :span="8" class="col-words">
                <span>{{ auditForm.presales ? auditForm.presales + '（元）' : '' }}</span>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-row v-if="transForm.default.formType == 'Contract'">
        <el-col style="padding-bottom: 10px">
          <span class="card_title">表单内容</span>
          <el-card shadow="always">
            <contract-detail ref="contract" :trans-form="transForm?transForm.default:null" :renewal="renewal" @contentChang="ctrFormPassChange" />
          </el-card>
        </el-col>
      </el-row>
      <el-row v-if="transForm.default.formType == 'AccPay'">
        <el-col style="padding-bottom: 10px">
          <span class="card_title">表单内容</span>
          <el-card shadow="always">
            <acc-pay ref="accPay" step="add" @baseRefresh="baseRefresh" />
          </el-card>
        </el-col>
      </el-row>
      <el-row v-if="transForm.default.formType == 'RealApproval'">
        <el-col style="padding-bottom: 10px">
          <span class="card_title">表单内容</span>
<!--          <el-card shadow="always">-->
<!--            <approval-form ref="realApprove" :trans-form="transForm?transForm.default:null" @contentChang="realApprovalChange" />-->
<!--          </el-card>-->
        </el-col>
      </el-row>
      <el-row>
        <el-col style="padding-bottom: 10px">
          <span class="card_title">申请内容</span>
          <el-card shadow="always" style="padding: 15px 5px 5px 15px">
            <el-row>
              <el-col :span="3" class="col-txt"><span>申请理由</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item prop="reason">
                  <el-input v-model="auditForm.reason" type="textarea" :rows="1">
                    启动商机
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3" class="col-txt"><span>备注说明</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item>
                  <el-input v-model="auditForm.comment" type="textarea" :rows="2" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3" class="col-txt"><span>附件上传</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item>
                  <el-upload
                    ref="upload"
                    class="upload-demo"
                    :action="$constant.BASE_URI + '/FileController/upload'"
                    :http-request="uploadHandleFile"
                    :before-remove="beforeRemove"
                    :limit="3"
                    multiple
                    :file-list="fileUrlList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">请上传50MB以内的文件</div>
                    <div slot="file" slot-scope="{file}">
                      <a :href="file.url">{{ file.name }}</a>
                      <span class="el-upload-list__item-actions">
                        <i class="el-icon-delete" @click="handlePictureRemove(file,fileUrlList)" />
                      </span>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col style="padding-bottom: 10px">
          <span class="card_title">审核相关</span>
          <el-card shadow="always" style="padding: 15px 5px 5px 15px">
            <el-row v-if="auditType.key === $constant.AUDIT_TYPE.PRO_APPROVE.key||auditType.key === $constant.AUDIT_TYPE.SIGN.key||auditType.key === $constant.AUDIT_TYPE.ENDING.key">
              <el-col :span="3" class="col-txt"><span>下一步审核人</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item prop="currAuditBy">
                  <el-select v-model="auditForm.currAuditBy" placeholder="审核人">
                    <el-option
                      v-for="item in UserData"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-else-if="auditType.key === $constant.AUDIT_TYPE.PRIOR_UP.key">
              <el-col :span="3" class="col-txt"><span>下一步审核人</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item prop="currAuditBy">
                  <el-select v-model="auditForm.currAuditBy" placeholder="审核人">
                    <el-option
                      v-for="item in UserData2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col :span="3" class="col-txt"><span>下一步审核人</span></el-col>
              <el-col :span="20" class="col-input">
                <el-form-item prop="currAuditBy">
                  <user-select :default-select="selectList" :disab="selectDisable" :multiple="false" width="700" @selectValue="parentMethod" />
                  <!--                  <el-select v-model="auditForm.currAuditBy" placeholder="审核人">
                                      <el-option
                                        v-for="item in UserData"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                      />
                                    </el-select>-->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3" class="col-txt"><span>创建日期</span></el-col>
              <el-col :span="8" class="col-input">
                <el-form-item>
                  <el-input v-model="auditForm.applytimeStr" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="3" class="col-txt"><span>创建人</span></el-col>
              <el-col :span="9" class="col-input">
                <el-form-item>
                  <el-input v-model="auditForm.applyname" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <div class="el-dialog__footer">
      <el-button @click="handleClose()">取 消</el-button>
      <el-button v-preventReClick type="primary" @click.native="handleCommit()">{{ onceCommit?'重新申请':'确 定' }}</el-button>
    </div>
  </div>
</template>

<script>
import channel, { upload } from '../../../static/utils/channel'
import Constant from '../../../static/utils/constant'
import UserSelect from '@/views/components/UserSelect'
import ContractDetail from '../../form/ctrForm'
import AccPay from '../../form/apForm'
import Base from '@/views/base/base'
import BaseData from '@/views/base/baseData'

export default {
    name: 'AuditApplyNew',
    components: {
        ContractDetail,
        AccPay,
        UserSelect,
    },
    mixins: [Base, BaseData],
    props: {
        referenceId: {
            type: String,
            default: ''
        },
        auditTarget: {
            type: String,
            default: 'Project'
        },
        auditType: {
            type: Object,
            default: null
        },
        formType: {
            type: String,
            default: ''
        },
        // 续签标记（1：为续签）
        renewal: {
            type: String,
            default: ''
        },
        // 表单过程数据 (预算编制审核)
        auditData: {
            type: Object,
            default() {
                return {}
            }
        }
    },
    data() {
        return {
            dc_key: ['PRO_TYPE'],
            enableStatus: '2',
            dc_project_status: Constant.dc_project_status,
            dc_sign_status_all: Constant.dc_sign_status_2,
            UserData: [],
            UserData2: [],
            selectList: [],
            fileUrlList: [],
            loading: false,
            selectDisable: false,
            UserMap: {},
            auditForm: this.getProjectForm(),
            auditRules: {
                reason: [{ required: true, trigger: 'blur', message: '请输入申请原因' }],
                currAuditBy: [{ required: true, trigger: 'blur', message: '请选择下一步审核人' }]
            },
            realApproval: false,
            ctrFormPass: false,
            onceCommit: false,

            transForm: this.getAuditForm(this.referenceId, this.auditType, true)
        }
    },
    watch: {
        referenceId: {
            deep: true,
            handler(val) {
                this.getData(val)
            }
        },
        // formType: {
        //     deep: true,
        //     handler(val) {
        //         this.getData(this.referenceId)
        //     }
        // },
        auditType: {
            deep: true,
            handler(val) {
                this.initForm(val)
            }
        }
    },
    mounted() {
        this.generateDcMap()
        this.initProType().then((res) => {
            this.$nextTick(() => {
                this.initUser().then(() => {
                    this.getData(this.referenceId)
                    this.initForm(this.auditType)
                })
            })
        })
    },
    methods: {
        parentMethod: function(val) {
            if (val.length > 0) {
                this.auditForm.currAuditBy = val.join(',')
            }
        },
        baseRefresh: function(val) {
            console.log(val)
            if (this.auditForm && val) {
                this.auditForm.proname = val.proName
                this.auditForm.custname = val.custName
            }
        },
        getData: function(val) {
            if (this.auditTarget === 'Project' || this.auditTarget === 'BudgetMaking') {
                const postData = {
                    id: val
                }
                this.loading = true
                channel.globleRequest('ProMainController', 'selectVoByPrimaryKey', postData, 'Project').then((res) => {
                    if (res.data) {
                        this.auditForm = this.getProjectForm(res.data)
                        console.log(this.auditForm)
                        if (this.formType == 'Prior' && this.auditForm.managedby) {
                            const manage = this.auditForm.managedby ? this.auditForm.managedby.split(',') : []
                            // if (manage.length === 1) {
                            //     this.selectDisable = true
                            //     this.selectList = manage
                            // } else if (manage.length > 1) {
                            //     this.selectDisable = false
                            //     this.selectList = manage
                            // }
                            this.initUser2(manage)
                        } else if (this.formType === 'Ending') {
                            channel.globleRequest('FlowAuditDetailController', 'getCheckUserByEnding', { groupId: this.$common.currUser().groupId }, 'Project').then((res) => {
                                if (res.data) {
                                    this.selectList.push(res.data.id)
                                    this.auditForm.currAuditBy = res.data.id
                                }
                            })
                        } else {
                            this.selectDisable = false
                        }
                    }
                    this.loading = false
                }).catch(() => {
                    this.loading = false
                })
            } else if (this.auditTarget === 'OutSource') {
                this.auditForm = this.getAccPayForm()
            }
        },
        /* 辅助相关*/
        initUser2: function(userIds) {
            const _this = this
            this.UserData2 = []
            this.UserMap2 = {}
            const post = {
                groupId: _this.$common.currUser() ? _this.$common.currUser().groupId : ''
            }
            return channel.globleRequest('SysUserExtendController', 'listAll', post, 'Pending Audit get user').then((res) => {
                if (res.data) {
                    res.data.forEach(function(item) {
                        if (userIds.indexOf(item.id) > -1) {
                            const json = {
                                label: item.truename,
                                value: item.id
                            }
                            _this.UserData2.push(json)
                            _this.UserMap2[json.value] = json.label
                        }
                    })
                }
            }).catch(() => {
            })
        },
        initForm: function(_auditType) {
            this.transForm = this.getAuditForm(this.referenceId, _auditType, true)
        },
        handleClose: function() {
            this.$emit('handleApplyClose')
        },
        /* 申请立项*/
        handleCommit: function() {
            this.$refs.auditForm.validate(valid => {
                if (valid) {
                    // @Todo 流程启动，表单及类型
                    this.auditApplyAdd(this.auditForm, this.auditType)
                } else {
                    return false
                }
            })
        },
        auditApplyAdd: function(_val, _auditType) {
            const _this = this
            // 构建子表单数据
            const form = this.getAuditForm(_val.id, _auditType, false)

            // 构建目标表单数据
            let tId = _val.id
            if (this.auditTarget === 'OutSource') {
                tId = form.default.id
            }
            const target = this.getTarget(tId, _auditType)
            target.protype = _val.protype
            target.protypeId = _val.protypeId
            // 通用信息项
            const content = {
                proName: _val.proname,
                cusName: _val.custname
            }

            // 审批信息项
            const auditData = {
                auditType: _auditType.key,
                auditName: _auditType.name,
                auditTarget: this.$common.castString(target),
                auditForm: this.$common.castString(form),
                referenceId: _val.id,
                referenceContent: this.$common.castString(content),
                applyBy: _val.applyBy,
                currAuditBy: _val.currAuditBy,
                groupId: this.$common.currUser().groupId,
                auditStatus: '0'
            }

            // 审批过程子项
            const auditDetailData = {
                reason: _val.reason,
                comment: _val.comment,
                auditedBy: _val.applyBy,
                nextTo: _val.currAuditBy,
                auditResult: '0',
                groupId: this.$common.currUser().groupId
            }
            if (this.fileUrlList.length) {
                auditDetailData.auditFile = JSON.stringify(this.fileUrlList)
            }
            if (_this.ctrFormPass) {
                _this.$message.warning('合同信息中带*项必填')
                return
            }
            if (_this.realApproval) {
                _this.$message.warning('请编制项目预算并且项目实施计划不能为空')
                return
            }
            channel.globleRequest('FlowAuditController', 'add', auditData, 'audit').then((res) => {
                if (res.data.auditId) {
                    auditDetailData.auditId = res.data.auditId
                    channel.globleRequest('FlowAuditDetailController', 'add', auditDetailData, 'audit detail')

                    if (_this.transForm.default.formType === 'Contract') {
                        _this.$refs.contract.addContract(form.default.id)
                    } else if (_this.transForm.default.formType === 'AccPay') {
                        _this.$refs.accPay.addAP(form.default.id)
                    } else if (_this.transForm.default.formType === 'RealApproval') {
                        _this.$refs.realApprove.addApproval(form.default.id)
                    }

                    if (target.processData) {
                        channel.globleRequest(target.target, target.op, target.processData, target.target).then((res) => {
                            _this.$emit('handleApplyCommit')
                        })
                    } else {
                        _this.$emit('handleApplyCommit')
                    }
                }
            }).catch(() => {
                _this.$emit('handleApplyCommit')
            })
        },
        getTarget: function(_id, _auditType) {
            const target = {
                id: _id
            }
            if (this.auditTarget === 'Project') {
                target.target = 'ProMainController'
                target.op = 'edit'
                if (_auditType.key === Constant.AUDIT_TYPE.PRO_APPROVE.key) {
                    target.processData = {
                        id: _id,
                        validstatus: '1'
                    }
                    target.passData = {
                        id: _id,
                        validstatus: '2',
                        realValidStatus: '0',
                        validat: true
                    }
                    target.refuseData = {
                        id: _id,
                        validstatus: '3',
                        validat: false
                    }
                } else if (_auditType.key === Constant.AUDIT_TYPE.SIGN.key) {
                    target.processData = {
                        id: _id,
                        signstatus: '1'
                    }
                    target.passData = {
                        id: _id,
                        signstatus: '3'
                    }
                    target.refuseData = {
                        id: _id,
                        signstatus: '0'
                    }
                } else if (_auditType.key === Constant.AUDIT_TYPE.PRIOR_UP.key) {
                    target.processData = {
                        id: _id,
                        signstatus: '7'
                    }
                    target.passData = {
                        id: _id,
                        signstatus: '2',
                        signat: true
                    }
                    target.refuseData = {
                        id: _id,
                        signstatus: '0'
                    }
                } else if (_auditType.key === Constant.AUDIT_TYPE.TENDER.key) {
                    target.processData = {
                        id: _id,
                        bidstatus: '1'
                    }
                    target.passData = {
                        id: _id,
                        bidstatus: '2',
                        bidat: true
                    }
                    target.refuseData = {
                        id: _id,
                        bidstatus: '0'
                    }
                } else if (_auditType.key === Constant.AUDIT_TYPE.ENDING.key) {
                    target.processData = {
                        id: _id,
                        enablestatus: '1'
                    }
                    target.passData = {
                        id: _id,
                        enablestatus: '2',
                        signstatus: '4',
                        prostatus: '2',
                        endingat: true
                    }
                    target.refuseData = {
                        id: _id,
                        enablestatus: '0'
                    }
                } else if (_auditType.key === Constant.AUDIT_TYPE.PRO_REAL_APPROVE.key) {
                    target.processData = {
                        id: _id,
                        realValidStatus: '1'
                    }
                    target.passData = {
                        id: _id,
                        realValidStatus: '2',
                        prostatus: '0',
                        realValidAt: true
                    }
                    target.refuseData = {
                        id: _id,
                        realValidStatus: '3',
                        realValidAt: false
                    }
                }
            } else if (this.auditTarget === 'OutSource') {
                target.target = 'AccPayableController'
                target.op = 'edit'
                if (_auditType.key === Constant.AUDIT_TYPE.ACC_PAY.key) {
                    target.passData = {
                        id: _id,
                        apStatus: '1'
                    }
                    target.refuseData = {
                        id: _id,
                        apStatus: '3'
                    }
                }
            } else if (this.auditTarget === 'BudgetMaking') {
                target.target = 'BudgetMakingController'
                target.op = 'editAudit'
                if (_auditType.key === Constant.AUDIT_TYPE.PRO_BUDGET_CHANGE.key) {
                    target.passData = {
                        proId: _id,
                        budgetStatus: '3'
                    }
                    target.refuseData = {
                        proId: _id,
                        budgetStatus: '4'
                    }
                }
            }

            return target
        },
        getAuditForm: function(_referenceId, _auditType, isAdd) {
            const _this = this
            const form = {
                default: {
                    referenceId: _referenceId,
                    referenceType: this.auditTarget,
                    isAdd: isAdd
                }
            }
            if (_auditType.key === Constant.AUDIT_TYPE.PRO_APPROVE.key) {
                form.default.controller = ''
                form.default.opQuery = ''
                form.default.formType = 'Approve'
            } else if (_auditType.key === Constant.AUDIT_TYPE.SIGN.key) {
                form.default.id = 'cid-' + String(new Date().getTime())
                form.default.controller = 'CtrMainController'
                form.default.opQuery = 'getById/' + form.default.id
                form.default.formType = 'Contract'
                form.default.opUpdate = 'edit'
                form.default.updateData = {
                    valid: '1'
                }
            } else if (_auditType.key === Constant.AUDIT_TYPE.PRIOR_UP.key) {
                form.default.controller = ''
                form.default.opQuery = ''
                form.default.formType = 'Prior'
            } else if (_auditType.key === Constant.AUDIT_TYPE.TENDER.key) {
                form.default.controller = ''
                form.default.opQuery = ''
                form.default.formType = 'Tender'
            } else if (_auditType.key === Constant.AUDIT_TYPE.ENDING.key) {
                form.default.controller = ''
                form.default.opQuery = ''
                form.default.formType = 'Ending'
            } else if (_auditType.key === Constant.AUDIT_TYPE.ACC_PAY.key) {
                form.default.id = 'aid-' + String(new Date().getTime())
                form.default.controller = 'AccPayableController'
                form.default.opQuery = 'getById/' + form.default.id
                form.default.formType = 'AccPay'
                form.default.opUpdate = 'edit'
                form.default.updateData = {
                    apStatus: '1'
                }
            } else if (_auditType.key === Constant.AUDIT_TYPE.PRO_REAL_APPROVE.key) {
                form.default.id = 'cid-' + String(new Date().getTime())
                form.default.controller = 'ProApprovalController'
                form.default.opQuery = 'getById/' + form.default.id
                form.default.formType = 'RealApproval'
                form.default.proId = _referenceId
                form.default.opUpdate = 'edit'
                form.default.updateData = {}
                this.getProApprovalByProId(_referenceId)
            } else if (_auditType.key === Constant.AUDIT_TYPE.PRO_BUDGET_CHANGE.key) {
                form.default.formType = 'BudgetMaking'
                form.default.cbList = this.auditData.cbList || []
                form.default.fyList = this.auditData.fyList || []
            }

            return form
        },
        getProjectForm: function(obj) {
            const currUser = this.$common.currUser()
            return {
                id: obj ? obj.id : '',
                proname: obj ? obj.proname : '',
                custname: obj ? obj.custname : '',
                protype: obj ? this.ProTypeMap[obj.protype] : '',
                protypeId: obj ? obj.protype : '',
                prostatus: obj ? this.dc_map.dc_project_status[obj.prostatus] : '',
                signStatus: obj ? this.dc_map.dc_sign_status_all[obj.signstatus] : '',
                presales: obj ? obj.presales : '',
                managedby: obj ? obj.managedby : '',
                reason: '',
                comment: '',
                currAuditBy: '',
                applyBy: currUser ? currUser.id : '',
                applyname: currUser ? currUser.truename : '',
                applytimeStr: this.$common.transDate(new Date().getTime())
            }
        },
        getAccPayForm: function(obj) {
            const currUser = this.$common.currUser()
            return {
                id: '',
                proname: '',
                custname: '',
                reason: '',
                comment: '',
                currAuditBy: '',
                applyBy: currUser ? currUser.id : '',
                applyname: currUser ? currUser.truename : '',
                applytimeStr: this.$common.transDate(new Date().getTime())
            }
        },
        realApprovalChange: function(val) {
            if (!val) {
                this.realApproval = true
            } else {
                this.realApproval = false
            }
        },

        ctrFormPassChange: function(val) {
            if (!val) {
                this.ctrFormPass = true
            } else {
                this.ctrFormPass = false
            }
        },
        generateDcMap: function() {
            this.dc_map['dc_project_status'] = this.$common.transDcMap(Constant.dc_project_status)
            this.dc_map['dc_sign_status_all'] = this.$common.transDcMap(Constant.dc_sign_status_2)
        },
        /* 辅助相关*/
        initUser: function() {
            const _this = this
            this.UserData = []
            this.UserMap = {}
            const post = {
                groupId: _this.$common.currUser() ? _this.$common.currUser().groupId : '',
                roleKey: 'XMCG'
            }
            return channel.globleRequest('SysUserExtendController', 'userByRoleData', post, 'Pending Audit get user').then((res) => {
                if (res.data) {
                    res.data.forEach(function(item) {
                        if (item.id) {
                            const json = {
                                label: item.trueName,
                                value: item.id
                            }
                            _this.UserData.push(json)
                            _this.UserMap[json.value] = json.label
                        }
                    })
                }
            }).catch(() => {
            })
        },

        getProApprovalByProId: async function(_referenceId) {
            const _this = this
            await this.$axios({
                headers: {
                    'MVVM-Key': String(new Date().getTime()),
                    'xx': 'anything'
                },
                method: 'post',
                url: _this.$constant.BASE_URI + '/ProApprovalController/getByProId/' + this.referenceId,
                data: {}
            }).then((res) => {
                if (res.data.id) {
                    _this.onceCommit = true
                }
            })
        },
        uploadHandleFile(param) {
            this.loading = true
            upload(param, true).then((res) => {
                if (res.key === 200) {
                    this.fileUrlList.push(res)
                    this.$message.info('文件上传成功')
                } else {
                    const uid = param.file.uid
                    const idx = this.$refs.upload.uploadFiles.findIndex(item => item.uid === uid)
                    this.$refs.upload.uploadFiles.splice(idx, 1)
                    this.$message.error('文件上传失败')
                }
                this.loading = false
            }).catch(() => {
                this.$message.error('文件上传异常!')
                this.loading = false
                const uid = param.file.uid
                const idx = this.$refs.upload.uploadFiles.findIndex(item => item.uid === uid)
                this.$refs.upload.uploadFiles.splice(idx, 1)
            })
        }
    }
}
</script>

<style scoped>
.audit-card {
    width: 70%;
}
.self {
    background: #95ec69;
}
.title {
    line-height: 28px;
}
.comment{
    line-height: 24px;
}
.text {
    font-size: 14px;
}

</style>

<style scoped lang="scss">
.AuditApply1{

.el-card__header {
    padding: 10px 20px;
}
.el-card__body {
    padding: 10px 20px;
}
.el-upload{
    width: 0 !important;
  }
    .el-upload-list li{
        text-align: left !important;
    }
}
</style>
