<template>
  <div class="auditDetail" style="width: 100%;height: 100%;padding: 5px">
    <el-form ref="infoForm" :model="infoForm" style="width: 100%;padding: 5px" :rules="auditRules">
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="申请详情" name="first">
          <el-row>
            <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>{{ infoForm.proName }}</span>
                  </el-col>
                  <el-col :span="4" class="col-txt"><span>客户名称</span></el-col>
                  <el-col :span="8" class="col-words">
                    <span>{{ infoForm.cusName }}</span>
                  </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">
                <el-row class="col-self">
                  <el-col :span="3" class="col-txt"><span>流程来源</span></el-col>
                  <el-col :span="20" class="col-input col-bg">
                    <span>{{ infoForm.auditType }}</span>
                  </el-col>
                </el-row>
                <el-row class="col-self">
                  <el-col :span="3" class="col-txt"><span>申请理由</span></el-col>
                  <el-col :span="20" class="col-input col-bg">
                    <el-input v-model="infoForm.apply.reason" disabled type="textarea" :rows="2" />
                    <!--                    <span>{{ infoForm.apply.reason }}</span>-->
                  </el-col>
                </el-row>
                <el-row class="col-self">
                  <el-col :span="3" class="col-txt"><span>申请说明</span></el-col>
                  <el-col :span="20" class="col-input col-bg">
                    <el-input v-model=" infoForm.apply.comment " disabled type="textarea" :rows="2" />
                    <!--                    <span>{{ infoForm.apply.comment }}</span>-->
                  </el-col>
                </el-row>
                <el-row class="col-self">
                  <el-col :span="3" class="col-txt"><span>附件</span></el-col>
                  <el-col :span="20" class="col-input col-bg">
                    <div v-for="file in fileUrlList" :key="file.data">
                      <a :href="file.url">{{ file.name }}</a>
                    </div>
                  </el-col>
                </el-row>
                <el-row class="col-self">
                  <el-col :span="3" class="col-txt"><span>申请人</span></el-col>
                  <el-col :span="10" class="col-input col-bg">
                    <span>{{ infoForm.apply.auditedBy }}</span>
                  </el-col>
                  <el-col :span="5" class="col-txt"><span>申请时间</span></el-col>
                  <el-col :span="5" class="col-input col-bg">
                    <span>{{ infoForm.apply.auditedAt }}</span>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
          <el-row v-if="!isView">
            <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="20" class="col-input">
                    <el-form-item>
                      <el-radio-group v-model="infoForm.auditResult" size="small" @change="updateReason">
                        <el-radio-button label="0">转交</el-radio-button>
                        <el-radio-button label="1">通过</el-radio-button>
                        <el-radio-button label="2">不通过</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="infoForm.auditResult == '0'">
                  <el-col :span="3" class="col-txt"><span>下一步审批人</span></el-col>
                  <el-col :span="20" class="col-input">
                    <el-form-item prop="auditNextTo">
                      <el-select v-model="infoForm.auditNextTo" 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="20" class="col-input">
                    <el-form-item prop="auditReason">
                      <el-input v-model="infoForm.auditReason" />
                    </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="infoForm.auditComment" class="conn" type="textarea" :rows="2" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane :label="formTitle" name="third">
          <el-row v-if="infoForm.auditForm && (infoForm.auditForm.default.formType == 'Approve'||infoForm.auditForm.default.formType == 'Prior')">
            <el-col style="padding-bottom: 10px">
              <span class="card_title">表单详情</span>
              <el-card shadow="always">
                <cust-form-main :cus-main="infoForm.auditForm.default" />
              </el-card>
            </el-col>
          </el-row>
          <el-row v-if="infoForm.auditForm && infoForm.auditForm.default.formType == 'Contract'">
            <el-col style="padding-bottom: 10px">
              <span class="card_title">合同内容</span>
              <el-card shadow="always">
                <contract-detail :trans-form="infoForm.auditForm.default" />
              </el-card>
            </el-col>
          </el-row>
          <el-row v-if="infoForm.auditForm && infoForm.auditForm.default.formType == 'AccPay'">
            <el-col style="padding-bottom: 10px">
              <span class="card_title">应付详情</span>
              <el-card shadow="always">
                <acc-pay :reference-id="infoForm.auditForm.default.id" step="view" />
              </el-card>
            </el-col>
          </el-row>
          <el-row v-if="infoForm.auditForm && infoForm.auditForm.default.formType == 'RealApproval'">
            <el-col style="padding-bottom: 10px">
              <span class="card_title">立项内容</span>
              <el-card shadow="always">
                <approval-form :trans-form="infoForm.auditForm.default" :is-view="true" />
              </el-card>
            </el-col>
          </el-row>
          <el-row v-if="infoForm.auditForm && infoForm.auditForm.default.formType == 'BudgetMaking'">
            <el-col style="padding-bottom: 10px">
              <span class="card_title">预算变更</span>
              <el-card shadow="always">
                <budgeting ref="budgeting" :pro-id="infoForm.auditForm.default.referenceId" :audit-data="infoForm.auditForm.default" :is-detail="true" :is-audit="'true'" />
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="审批过程" name="second">
          <el-row v-for="userAudit in infoForm.auditList" style="margin-bottom: 10px">
            <el-col v-if="userAudit.auditedBy != currUserId" :span="3" class="col-txt">
              <span>{{ userAudit.auditedByName }}</span><br>
              <span class="f-tiny">{{ userAudit.auditedAt }}</span>
            </el-col>
            <el-col v-if="userAudit.auditedBy != currUserId" :span="20" class="col-input">
              <el-card class="audit-card">
                <div slot="header" class="text title">
                  <span class="ftb">{{ userAudit.reason }}</span>
                  <!--<span class="fr">{{ userAudit.auditedAt }}</span>-->
                </div>
                <div class="pr text comment">
                  <div>
                    <span class="ftb">{{ userAudit.comment }}</span>
                  </div>
                  <div class="fr f-small">
                    <div>审批状态：{{ userAudit.resultStr }}</div>
                    <div v-if="userAudit.result =='0'" class="p-gray">下一步审批人：{{ userAudit.nextTo }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col v-if="userAudit.auditedBy == currUserId" :span="20" class="col-txt">
              <el-card class="audit-card fr self">
                <div slot="header" class="text title">
                  <span class="ftb">{{ userAudit.reason }}</span>
                </div>
                <div class="pr text comment">
                  <div>
                    <span class="ftb">{{ userAudit.comment }}</span>
                  </div>
                  <div class="fl f-small">
                    <div>审批状态：{{ userAudit.resultStr }}</div>
                    <div v-if="userAudit.result =='0'" class="p-lightgray">下一步审批人：{{ userAudit.nextTo }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col v-if="userAudit.auditedBy == currUserId" :span="3" class="col-input">
              <span>{{ userAudit.auditedByName }}(本人)</span><br>
              <span class="f-tiny">{{ userAudit.auditedAt }}</span>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="el-dialog__footer">
      <el-button @click="handleClose()">取 消</el-button>
      <el-button v-if="!isView" type="primary" @click="handleCommit()">确 定</el-button>
    </div>
    <el-dialog
      title="消息"
      :visible.sync="dialogVisible"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      :before-close="handleMessageClose"
    >
      <span>储备项目确认成功，请先分配售前负责人或项目经理！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseCommit()">分配售前负责人或项目经理</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="消息"
      :visible.sync="dialogSqVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      :before-close="handleSqMessageClose"
    >
      <span>售前负责人或项目经理已分配，继续指派任务吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCreateTask()">创建售前任务</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="dialogTaskTitle" :visible.sync="dialogTaskVisible" width="70%" top="50px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <task-form :key="taskFormKey" :task-info="taskInfo" @handleClose="handleTaskClose" @handleCommit="handleTaskCommit" />
    </el-dialog>
    <el-dialog :title="dialogTitleFp" :visible.sync="dialogVisibleFp" width="70%" top="50px"  :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <pro-distribution-form :key="distKey" :pro-id="proId" @handleClose="handleFpClose" @handleCommit="handleFpCommit" />
    </el-dialog>
  </div>
</template>

<script>
import channel from '../../../static/utils/channel'
import Constant from '../../../static/utils/constant'
import ContractDetail from '../../form/ctrForm'
import AccPay from '../../form/apForm'
import TaskForm from '@/views/task/taskForm'
import ApprovalForm from '../../project/proApprovalForm'
import CustFormMain from '@/views/crm/custFormMain'
import Budgeting from '@/views/projectDashboard/components/morecom/budgeting'
import ProDistributionForm from '@/views/plan-2/proDistributionForm'
import Base from '@/views/base/base'
import BaseData from '@/views/base/baseData'
export default {
    name: 'AuditDetail',
    components: {
        ContractDetail, AccPay, TaskForm, ApprovalForm,
        CustFormMain,
        Budgeting,
        ProDistributionForm
    },
    mixins: [Base, BaseData],
    props: {
        auditId: {
            type: String,
            default: ''
        },
        isView: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            // 通用字典项
            dc_flow_status: Constant.dc_flow_status,
            AUDIT_TYPE: [],
            dc_map: {},
            // 业务相关
            currUserId: '',
            formType: '',
            UserData: [],
            fileUrlList: [],
            UserMap: {},
            activeName: 'first',
            infoForm: this.getBaseForm(),
            auditRules: {
                auditNextTo: [{ required: true, trigger: 'blur', message: '请输入下一步审批人' }],
                auditReason: [{ required: true, trigger: 'blur', message: '请输入审批意见' }]
            },
            proId: '',
            protype: '',
            taskFormKey: 0,
            dialogTaskTitle: '创建任务',
            dialogTaskVisible: false,
            dialogTitleFp: '项目分配',
            dialogVisibleFp: false,
            distKey: 0,
            taskInfo: {
                id: '',
                batchId: '',
                proId: '',
                proType: '',
                batchName: '',
                type: '1'
            },
            dialogVisible: false,
            dialogSqVisible: false,
            // 表单相关
            formTitle: '表单详情'

        }
    },
    watch: {
        auditId: {
            deep: true,
            handler(val) {
                this.getData(val)
            }
        }
    },

    mounted() {
        this.generateDcMap()
        this.$nextTick(() => {
            this.initValue()
            this.initUser().then(() => {
                this.getData(this.auditId)
            })
        })
    },
    methods: {
        initValue: function() {
            const currUser = this.$common.currUser()
            if (currUser) {
                this.currUserId = currUser.id
            }
        },
        getData: function(_auditId) {
            const _this = this
            this.infoForm = this.getBaseForm()
            const postData = {
                id: _auditId
            }
            _this.fileUrlList = []
            this.baseRequest('getById', postData).then((res) => {
                if (res.data) {
                    const data = res.data
                    _this.proId = data.referenceId
                    // 审核的表单部分
                    const referenceContent = _this.$common.castEval(data.referenceContent)
                    if (referenceContent) {
                        _this.infoForm.proName = referenceContent.proName
                        _this.infoForm.cusName = referenceContent.cusName
                    }

                    if (data.auditType === Constant.AUDIT_TYPE.SIGN.key) {
                        _this.formType = 'Contract'
                    }
                    _this.infoForm.auditType = _this.dc_map.AUDIT_TYPE[data.auditType]
                    _this.infoForm.auditForm = _this.$common.castEval(data.auditForm)
                    _this.infoForm.auditTarget = _this.$common.castEval(data.auditTarget)
                    _this.protype = _this.infoForm.auditTarget.protypeId
                    console.log('_this.infoForm.auditTarget.protype')
                    console.log(_this.infoForm)
                    _this.infoForm.auditedList = data.auditedList

                    if (_this.infoForm.auditForm) {
                        if (_this.infoForm.auditForm.default.formType === 'Contract') {
                            _this.formTitle = '合同详情'
                        } else if (_this.infoForm.auditForm.default.formType === 'AccPay') {
                            _this.formTitle = '应付详情'
                        } else if (_this.infoForm.auditForm.default.formType === 'RealApproval') {
                            _this.infoForm.auditForm.default.referenceId = _this.infoForm.auditForm.default.proId
                            _this.formTitle = '立项详情'
                        } else if (_this.infoForm.auditForm.default.formType === 'Approve' || _this.infoForm.auditForm.default.formType === 'Prior') {
                            _this.infoForm.auditForm.default.cusName = _this.infoForm.cusName
                            _this.formTitle = '表单详情'
                        } else {
                            _this.formTitle = '表单详情'
                        }
                    }
                    // 审核的通用部分
                    const detailPostData = {
                        auditId: _auditId
                    }

                    channel.globleRequest('FlowAuditDetailController', 'listAll', detailPostData, 'Audit Detail').then((res) => {
                        if (res.data) {
                            const detailList = res.data
                            if (detailList.length > 0) {
                                _this.infoForm.apply.reason = detailList[0].reason
                                _this.infoForm.apply.comment = detailList[0].comment
                                _this.infoForm.apply.auditedAt = _this.$common.transDate(detailList[0].createdAt, 'yyyy/MM/dd hh:mm')
                                _this.infoForm.apply.auditedBy = _this.UserMap[detailList[0].auditedBy]
                                if (detailList[0].auditFile) {
                                    _this.fileUrlList = JSON.parse(detailList[0].auditFile)
                                    console.log(_this.fileUrlList)
                                }
                            }
                            detailList.forEach(function(item) {
                                const detail = {
                                    auditedBy: item.auditedBy,
                                    auditedByName: _this.UserMap[item.auditedBy],
                                    auditedAt: _this.$common.transDate(item.createdAt, 'yyyy/MM/dd hh:mm'),
                                    reason: item.reason,
                                    comment: item.comment,
                                    result: item.auditResult,
                                    nextTo: item.nextTo ? _this.UserMap[item.nextTo] : ''
                                }
                                if (detail.result === '0') {
                                    detail.resultStr = '转交'
                                } else if (detail.result === '1') {
                                    detail.resultStr = '通过'
                                } else if (detail.result === '2') {
                                    detail.resultStr = '不通过'
                                }

                                _this.infoForm.auditList.push(detail)
                            })
                        }
                    }).catch(() => {
                    })
                }
            }).then(() => {
                this.$nextTick(() => {
                    this.$refs.budgeting.initData()
                })
            }).catch(() => {
            })
        },
        handleClose: function() {
            this.$emit('handleAuditClose')
        },
        handleMessageClose: function() {
            this.dialogVisible = false
        },
        handleSqMessageClose: function() {
            this.dialogSqVisible = false
        },
        handleTaskClose: function() {
            this.dialogTaskVisible = false
        },
        handleFpClose: function() {
            this.dialogVisibleFp = false
        },
        handleTaskCommit: function() {
            this.dialogTaskVisible = false
        },
        handleFpCommit: function() {
            this.dialogVisibleFp = false
            this.dialogSqVisible = true
        },
        handleCreateTask: function() {
            this.taskFormKey++
            this.taskInfo.proId = this.proId
            this.taskInfo.proType = this.protype
            this.dialogVisible = false
            this.dialogSqVisible = false
            this.dialogTaskVisible = true
        },
        handleCommit: function() {
            if (this.infoForm.auditForm && this.infoForm.auditForm.default.formType == 'Approve') {
                if (this.infoForm.auditResult == '1') {
                    this.dialogVisible = true
                }
            }
            this.handleCommit1()
        },
        handleCloseCommit: function() {
            this.dialogVisible = false
            this.distKey++
            this.dialogVisibleFp = true
        },
        handleCommit1: function() {
            const _this = this
            this.$refs.infoForm.validate(valid => {
                if (valid) {
                    const auditData = {
                        auditStatus: _this.infoForm.auditResult,
                        auditedList: _this.infoForm.auditedList + ',' + _this.currUserId + ',',
                        currAuditBy: _this.infoForm.auditResult === '0' ? _this.infoForm.auditNextTo : '',
                        id: _this.auditId
                    }
                    const auditDetailData = {
                        reason: _this.infoForm.auditReason,
                        comment: _this.infoForm.auditComment,
                        auditedBy: _this.currUserId,
                        nextTo: _this.infoForm.auditNextTo,
                        auditResult: _this.infoForm.auditResult,
                        auditId: _this.auditId
                    }

                    _this.baseRequest('edit', auditData).then((res) => {
                        if (res.data) {
                            channel.globleRequest('FlowAuditDetailController', 'add', auditDetailData, 'audit detail')
                            if (_this.infoForm.auditResult !== '0') {
                                // @FIXME 审核目标的更新，如果没有审核目标则略过
                                const target = _this.infoForm.auditTarget
                                if (target) {
                                    let targetData = target.passData
                                    if (_this.infoForm.auditResult === '2') {
                                        targetData = target.refuseData
                                    }
                                    if (targetData.validat) {
                                        targetData.validat = _this.$common.transServDate(new Date())
                                    } else if (targetData.signat) {
                                        targetData.signat = _this.$common.transServDate(new Date())
                                    } else if (targetData.bidat) {
                                        targetData.bidat = _this.$common.transServDate(new Date())
                                    } else if (targetData.endingat) {
                                        targetData.endingat = _this.$common.transServDate(new Date())
                                    } else if (targetData.realValidAt) {
                                        targetData.realValidAt = _this.$common.transServDate(new Date())
                                    }
                                    console.log('update target:', targetData)
                                    channel.globleRequest(target.target, target.op, targetData, target.target)
                                }

                                if (_this.infoForm.auditResult === '1') {
                                    const form = _this.infoForm.auditForm
                                    if (form.default.opUpdate && form.default.updateData) {
                                        const defaultForm = form.default
                                        // @Todo 这里以Contract/AccPay之类的标准表单作了类定制化，后期需再进行调整
                                        channel.globleRequest(defaultForm.controller, defaultForm.opQuery, '', defaultForm.controller).then((res) => {
                                            if (res.data) {
                                                const updateData = defaultForm.updateData
                                                updateData.id = res.data.id
                                                channel.globleRequest(defaultForm.controller, defaultForm.opUpdate, updateData, defaultForm.controller)
                                            }
                                        })
                                    }
                                }
                            }
                        }
                        console.log(this.infoForm)
                        _this.$emit('handleAuditCommit')
                    }).catch(() => {
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        getBaseForm: function() {
            const form = {
                proName: '',
                cusName: '',
                auditType: '',
                auditedList: '',
                apply: {
                    reason: '',
                    comment: '',
                    auditedBy: '',
                    auditedAt: ''
                },
                auditForm: null,
                auditTarget: null,
                auditResult: '1',
                auditReason: '同意',
                auditComment: '',
                auditNextTo: '',

                auditList: []
            }
            return form
        },
        updateReason: function(val) {
            if (val === '0') {
                this.infoForm.auditReason = '转交'
            } else if (val === '1') {
                this.infoForm.auditReason = '同意'
            } else if (val === '2') {
                this.infoForm.auditReason = '不同意'
            }
        },
        // /* 辅助相关*/
        // initUser: function() {
        //     const _this = this
        //     this.UserData = []
        //     this.UserMap = {}
        //
        //     return channel.globleRequest('SysUserExtendController', 'listAll', '', 'Pending Audit get user').then((res) => {
        //         if (res.data) {
        //             res.data.forEach(function(item) {
        //                 const json = {
        //                     label: item.truename,
        //                     value: item.id
        //                 }
        //                 _this.UserData.push(json)
        //                 _this.UserMap[json.value] = json.label
        //             })
        //         }
        //     }).catch(() => {
        //     })
        // },
        generateDcMap: function() {
            this.AUDIT_TYPE = []
            for (const key in Constant.AUDIT_TYPE) {
                const json = {
                    label: Constant.AUDIT_TYPE[key].name,
                    value: Constant.AUDIT_TYPE[key].key
                }
                this.AUDIT_TYPE.push(json)
            }
            this.dc_map['dc_flow_status'] = this.$common.transDcMap(Constant.dc_flow_status)
            this.dc_map['AUDIT_TYPE'] = this.$common.transDcMap(this.AUDIT_TYPE)
        },
        baseRequest(opUrl, postData) {
            return channel.globleRequest('FlowAuditController', opUrl, postData, 'audit')
        }
    }
}
</script>

<!--<style scoped>-->
<!--    .audit-card {-->
<!--        width: 70%;-->
<!--    }-->
<!--    .self {-->
<!--        /*background: #95ec69;*/-->
<!--        background: #4e7ebf9c;-->
<!--        color: white;-->
<!--    }-->
<!--    .title {-->
<!--        line-height: 20px;-->
<!--    }-->
<!--    .comment{-->
<!--        line-height: 24px;-->
<!--    }-->
<!--    .text {-->
<!--        font-size: 14px;-->
<!--    }-->

<!--</style>-->

<style lang="scss">
    .auditDetail{
         .el-textarea__inner{
            border-color: rgba(0,0,0,0) !important;
        }
        .conn .el-textarea__inner{
            border-color: #C0C4CC !important;
        }
        .audit-card {
            width: 70%;
        }
        .self {
            /*background: #95ec69;*/
            background: #4e7ebf9c;
            color: white;
        }
        .title {
            line-height: 20px;
        }
        .comment{
            line-height: 24px;
        }
        .text {
            font-size: 14px;
        }
    }
    .el-card__header {
        padding: 10px 20px;
    }
    .el-card__body {
        padding: 10px 20px;
    }
    .ftb{
        word-wrap: break-word;
        word-break: break-all;
        white-space: pre-wrap !important;
        //text-align: left;
    }
</style>
