<#assign base=request.contextPath />
<#import "../../common/defaultLayout.ftl" as defaultLayout>
<@defaultLayout.layout>
  <link rel="stylesheet" href="${base}/element-ui/element-ui.css">
  <style>

      .el-upload__input {
          display: none !important;
      }

      .el-textarea .el-input__count {
          line-height: 15px;
      }

      .admin-content-body {
          margin-bottom: 100px;
      }

      .el-table__empty-block {
          height: 60px !important;
      }

      .el-radio-button__inner, .el-radio-group {
          line-height: unset;
      }

      .el-upload-list__item-name [class^="el-icon"] {
          height: unset;
      }

      .el-tag--small {
          margin-right: 5px;
      }

      [v-cloak] {
          display: none;
      }

      .popover-overflow {
          overflow-y: scroll;
          max-height: 400px
      }
  </style>

  <div class="admin-content" id="app" v-cloak>
    <div class="admin-content-body">
      <div class="am-cf am-padding">
        <div class="am-fl am-cf"><strong class="am-text-primary am-text-lg">业务应用</strong> /
          <small>${process.processType.description}详情</small>
        </div>
      </div>

      <div class="am-u-sm-12 am-u-md-12">

        <el-descriptions title="${process.processType.description}详情" v-cloak>
          <el-descriptions-item label="项目编号">{{process.projectNo}}</el-descriptions-item>
          <el-descriptions-item label="标题">
            <el-popover placement="top-start" title="标题" width="400" trigger="hover" :content="process.projectTitle">
              <span slot="reference">{{process.projectTitle|ellipsis(28)}}</span>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{process.applyDate}}</el-descriptions-item>
          <el-descriptions-item label="项目类型">${projectType}</el-descriptions-item>
          <el-descriptions-item label="合作类型">${cooperationType}</el-descriptions-item>
          <el-descriptions-item label="采购类型" v-if="isProcurementContract">
              <#if contract.procurementMode??>
                  ${contract.procurementMode.description}
              </#if>
          </el-descriptions-item>
          <el-descriptions-item label="申请部门">{{process?.applyDept?.split(',').join('/')}}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{process.applyPersonName}}</el-descriptions-item>
          <el-descriptions-item label="申请部门领导">{{process.applyDeptLeaderName}}</el-descriptions-item>
          <el-descriptions-item label="申请人电话" v-if="isSaleContract">{{contract.applyPersonPhone}}</el-descriptions-item>

          <el-descriptions-item label="合同编号">
            <el-popover placement="top-start" title="合同编号" width="400" trigger="hover" :content="process.contractNo">
              <span slot="reference">{{process.contractNo|ellipsis}}</span>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="合同名称">
            <el-popover placement="top-start" title="合同名称" width="400" trigger="hover" :content="process.contractName">
              <span slot="reference">{{process.contractName|ellipsis}}</span>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="合同金额">{{contractAmount|numberFormat}}元</el-descriptions-item>

          <el-descriptions-item label="客户名称" v-if="isSaleContract">
            <el-popover placement="top-start" title="备客户名称注" width="400" trigger="hover" :content="contract.clientName">
              <span slot="reference">{{contract.clientName|ellipsis}}</span>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="供应商" v-if="isProcurementContract">{{contract.supplierName}}</el-descriptions-item>
          <el-descriptions-item label="最终用户名称">{{project.terminalCustomer}}</el-descriptions-item>

          <el-descriptions-item label="用印类型">
              <#assign sealTypes = process.sealTypes.list>
              <#if sealTypes?size==1>
                <el-tag size="small">${sealTypes[0].description}</el-tag>
              <#elseif sealTypes?size gt 1>
                <el-popover placement="top-start" title="用印类型" width="150" trigger="hover">
                  <a slot="reference">查看用印类型</a>
                    <#--展示已经上传的文件-->
                  <div style="margin-top: 10px">
                    <ul class="el-upload-list el-upload-list--text">
                        <#list sealTypes as item>
                          <li class="el-upload-list__item is-success">
                            <el-tag size="small">${item.description}</el-tag>
                          </li>
                        </#list>
                    </ul>
                  </div>
                </el-popover>
              <#else>
                <strong>没有用印类型</strong>
              </#if>

          </el-descriptions-item>

          <el-descriptions-item label="税率" v-if="process.taxRate">{{process.taxRate}}%</el-descriptions-item>
          <el-descriptions-item label="税率" v-else></el-descriptions-item>
          <el-descriptions-item label="是否垫资">${isPrepaid}</el-descriptions-item>
          <el-descriptions-item label="垫资金额" v-if="isPrepaid==='是'">{{repaidAmount|numberFormat}}元</el-descriptions-item>

          <el-descriptions-item label="预算毛利率">{{budgetGrossMargin}}%</el-descriptions-item>

          <el-descriptions-item label="收款条件" v-if="isSaleContract">
            <el-popover placement="top-start" title="收款条件" width="400" trigger="hover">
              <span slot="reference">{{contract.paymentTerms|ellipsis}}</span>
              <el-input type="textarea" readonly :autosize="{ minRows: 5, maxRows: 10}" cols="50" :value="contract.paymentTerms"></el-input>
            </el-popover>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="付款条件" v-if="isProcurementContract">
            <el-popover placement="top-start" title="付款条件" width="400" trigger="hover">
              <span slot="reference">{{contract.paymentTerms|ellipsis}}</span>
              <el-input type="textarea" readonly :autosize="{ minRows: 5, maxRows: 10}" cols="50" :value="contract.paymentTerms"></el-input>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            <el-popover placement="top-end" title="备注" width="400" trigger="hover">
              <span slot="reference">{{process.remark|ellipsis}}</span>
              <el-input type="textarea" readonly :autosize="{ minRows: 5, maxRows: 10}" cols="50" :value="process.remark"></el-input>
            </el-popover>
          </el-descriptions-item>
          <el-descriptions-item label="附件">
            <span v-if="isNotEmpty(attachments) && attachments.length===1" title="点击查看或下载">
              <a :href="attachments[0].uri" target="_blank">
                <el-tag size="small">
                  <i class="el-icon-document"></i>{{attachments[0].name|ellipsis(50)}}
                </el-tag>
              </a>
            </span>

            <el-popover v-if="isNotEmpty(attachments) && attachments.length > 1"
                        placement="top-start" title="上传的附件" width="380" trigger="hover">
              <a slot="reference">查看附件列表</a>
                <#--展示已经上传的文件-->
              <div style="margin-top: 10px">
                <ul class="el-upload-list el-upload-list--text">
                  <li class="el-upload-list__item is-success" v-for="attachment in attachments"
                      :key="attachment.name" title="点击查看或下载">
                    <a class="el-upload-list__item-name" :href="attachment.uri" target="_blank">
                      <i class="el-icon-document"></i>{{attachment.name|ellipsis(50)}}
                    </a>
                  </li>
                </ul>
              </div>
            </el-popover>
            <span v-if="isEmpty(attachments)"><strong>没有上传附件</strong></span>
          </el-descriptions-item>

        </el-descriptions>

          <#-- 项目预算收入明细表 -->
        <div v-if="isSaleContract">
          <el-alert title="项目预算收入明细" type="success" center :closable="false"></el-alert>

          <el-table border :data="incomeDetails" empty-text="暂无">
            <el-table-column type="index" :index="1" label="序号" fixed></el-table-column>
            <el-table-column prop="name" label="名称" fixed width="120"></el-table-column>
            <el-table-column prop="type" label="类别"></el-table-column>
            <el-table-column prop="spec" label="规格型号"></el-table-column>
            <el-table-column prop="param" label="参数"></el-table-column>
            <el-table-column prop="amount" label="数量"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
            <el-table-column prop="price" label="单价（元）" width="120"></el-table-column>
            <el-table-column prop="taxRate" label="税率（%）"></el-table-column>
            <el-table-column prop="totalTaxInclude" label="含税金额（元）" width="120"></el-table-column>
            <el-table-column prop="totalTaxExclude" label="不含税金额（元）" width="120"></el-table-column>
            <el-table-column prop="totalTax" label="税金（元）" width="120"></el-table-column>
            <el-table-column prop="expirationDate" label="质保期" width="150"></el-table-column>

          </el-table>

        </div>

          <#-- 供应商比选材料 -->

        <div v-if="isProcurementContract">
          <el-alert title="供应商比选材料" type="success" center :closable="false"></el-alert>
          <el-table border :data="supplierMaterials" empty-text="暂无">
            <el-table-column type="index" :index="1" label="序号" fixed></el-table-column>

            <el-table-column prop="companyName" label="公司名称" width="180" align="center"></el-table-column>
            <el-table-column prop="totalAmount" label="合计金额" width="160" align="center"></el-table-column>
            <el-table-column prop="serviceTerms" label="服务条款" width="180" align="center"></el-table-column>
            <el-table-column prop="paymentTerms" label="付款条件" align="center"></el-table-column>
            <el-table-column prop="taxRate" label="税率（%）" width="160" align="center"></el-table-column>
            <el-table-column prop="remark" label="备注" align="center"></el-table-column>
            <el-table-column prop="attachment" label="附件" align="center" width="150">
              <template slot-scope="scope">
                <el-popover v-if="isNotEmpty(scope.row.attachment)" placement="top-end" title="上传的附件" width="380" trigger="hover">
                  <el-button size="small" type="text" slot="reference">附件查看</el-button>
                    <#--展示已经上传的文件-->
                  <div style="margin-top: 10px">
                    <ul class="el-upload-list el-upload-list--text">
                      <li class="el-upload-list__item is-success" v-for="attachment in scope.row.attachment"
                          :key="attachment.name" title="点击查看或下载">
                        <a class="el-upload-list__item-name" :href="attachment.uri" target="_blank">
                          <i class="el-icon-document"></i>{{attachment.name|ellipsis(50)}}
                        </a>
                      </li>
                    </ul>
                  </div>
                </el-popover>

                <span v-else><strong>没有上传附件</strong></span>

              </template>
            </el-table-column>

          </el-table>

        </div>

          <#-- 采购详情 -->
        <div v-if="isProcurementContract">
          <el-alert title="采购清单" type="success" center :closable="false"></el-alert>

          <el-table border :data="procurementDetails" empty-text="暂无" row-key="rowKey" default-expand-all>
            <el-table-column type="index" :index="1" label="序号" fixed></el-table-column>
            <el-table-column prop="feeType" label="费用项目" fixed width="80"></el-table-column>
            <el-table-column prop="name" label="产品名称" fixed></el-table-column>
            <el-table-column prop="category" label="采购类别" fixed></el-table-column>

            <el-table-column prop="amount" label="数量"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
            <el-table-column prop="price" label="预算单价" width="100"></el-table-column>
            <el-table-column prop="taxRate" label="税率（%）"></el-table-column>
            <el-table-column prop="totalTaxInclude_" label="含税总金额（元）" width="120"></el-table-column>
            <el-table-column prop="totalTaxExclude" label="不含税金额（元）" width="120"></el-table-column>
            <el-table-column prop="totalTax" label="税金（元）" width="110"></el-table-column>
            <el-table-column prop="isUnderwrittenDesc" label="是否垫资"></el-table-column>
            <el-table-column prop="payTime" label="支出时间" width="160"></el-table-column>
            <el-table-column prop="payAmount" label="支出金额（元）" width="120"></el-table-column>
            <el-table-column prop="amountAlready" label="已采购数量" width="100"></el-table-column>
            <el-table-column prop="amountCurrent" label="本次采购数量" width="180"></el-table-column>
            <el-table-column prop="amountLeft" label="未采购数量" width="100"></el-table-column>

            <el-table-column prop="supplierName" label="供应商名称" width="200"></el-table-column>
            <el-table-column prop="manufacturerName" label="设备厂商名称" width="200"></el-table-column>
            <el-table-column prop="purchaseList" label="对应采购清单" width="200"></el-table-column>
            <el-table-column prop="spec" label="规格型号" width="200"></el-table-column>
            <el-table-column prop="procurementAmount" label="对应采购数目" width="200"></el-table-column>
            <el-table-column prop="procurementPrice" label="采购单价" width="200"></el-table-column>
            <el-table-column prop="totalTaxInclude" label="含税总金额（元）" width="200"></el-table-column>

          </el-table>

        </div>

        <el-row style="margin-top: 30px">
          <el-button type="info" @click="backLastPage">返回上一级</el-button>
            <#if forAudit>
              <el-button type="primary" @click="auditProcess">审核</el-button>
            </#if>
        </el-row>

        <el-dialog title="审核" :visible.sync="auditFormVisible" v-cloak destroy-on-close>
          <el-form ref="auditForm" :model="auditForm" label-width="80px">

            <el-form-item prop="processStatus" label="审核" :rules="[{ required: true, message: '还没审核'}]">
              <el-radio-group v-model="auditForm.processStatus">
                <el-radio label="audit_passed">审核通过</el-radio>
                <el-radio label="audit_not_passed">审核不通过</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item prop="auditOpinion" label="审核意见" :rules="[{ required: true, message: '审核意见不能为空'}]">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 10}"
                        maxlength="5000" v-model="auditForm.auditOpinion"
                        placeholder="请输入审核意见" cols="90"></el-input>
            </el-form-item>

          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitAudit">提交</el-button>
          </div>

        </el-dialog>

      </div>

    </div>

  </div>

  </div>

  <script src="${base}/vue/vue.js"></script>
  <script src="${base}/element-ui/element-ui.js"></script>

  <script>

    const isEmpty = (obj) => {
      if (!obj) {
        return true
      }

      if (obj.hasOwnProperty('length')) {
        return obj.length === 0
      }
      return false
    }

    const isNotEmpty = (obj) => {
      return !isEmpty(obj)
    }

    const isBlank = (obj) => {
      return isEmpty(obj) || (obj.trim && isEmpty(obj.trim()))
    }

    const hasText = (obj) => {
      return !isBlank(obj)
    }

    function checkStatus(response) {
      if (response.status >= 200 && response.status < 300) {
        return response
      }
      else {
        const error = new Error(response.statusText);
        error.response = response
        throw error
      }
    }

    function parseJSON(response) {
      return response.json()
    }

    function isImage(path) {
      return /\w.(png|jpg|jpeg|svg|webp|gif|bmp)$/i.test(path);
    }

    /**
     * 给定一个数字，保留两位小数输出，格式化为包含分隔符
     * @param f
     * @returns {string}
     */
    function numberFixed(f) {
      if (!f) {
        return "0.00";
      }
      //return Number(f).toFixed(2);
      //格式化413,423,423.24
      f = Number(f).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: true });
      return f;
    }

    const data = () => {
      return {
        process: {},
        project: {},
        auditForm: {
          processStatus: null
        },
        auditFormVisible: false,
        supplierMaterials: []
      }
    }

    const methods = {
      isBlank,
      hasText,
      isEmpty,
      isNotEmpty,
      backLastPage() {
        window.history.back();
      },
      loadProject(id) {
        const loading = this.$loading({
          lock: true,
          text: '正在加载项目',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        fetch("${base}/process/" + id)
            .then(checkStatus)
            .then(parseJSON)
            .then(data => {
              const {
                budgetGrossMargin, contractAmount,
                attachments, processId, isPrepaid, repaidAmount,
                incomeDetails, process, projectType, cooperationType,
                contract, supplierMaterials, procurementDetails, project
              } = data
              // 转换数据
              // @formatter:off
              const computeType = (type) => {
                switch (type) {
                  case 1: return '设备'
                  case 2: return '工程'
                  case 3: return '服务'
                  default: return '未知'
                }
              }
              const computeFeeType = (type) => {
                switch (type) {
                  case 1: return '设备'
                  case 2: return '施工'
                  case 3: return '服务'
                  case 4: return '其他'
                  default: return '未知'
                }
              }

              // @formatter:on

              const mapAttachment = attachment => {
                if (hasText(attachment)) {
                  try {
                    return JSON.parse(attachment).map(item => ({
                      ...item, isImage: isImage(item.name)
                    }))
                  } catch (e) {
                    return []
                  }
                }
                else {
                  return []
                }
              }

              this.process = process
              this.project = project
              this.isPrepaid = isPrepaid
              this.contractAmount = contractAmount
              this.repaidAmount = repaidAmount
              this.contract = contract
              this.processId = processId
              this.projectType = projectType
              this.cooperationType = cooperationType
              this.budgetGrossMargin = budgetGrossMargin
              this.supplierMaterials = supplierMaterials && supplierMaterials.map(item => ({
                ...item, attachment: mapAttachment(item.attachment),
                totalAmount: numberFixed(item.totalAmount),
              }))

              const convertCommon = detail => {
                return {
                  rowKey: rowKey++, feeType: computeFeeType(detail.type),
                  price: numberFixed(detail.price),
                  payAmount: numberFixed(detail.payAmount),
                  totalTaxExclude: numberFixed(detail.totalTaxExclude),
                  totalTaxInclude_: numberFixed(detail.totalTaxInclude),// 存在相同字段转换一下
                  totalTaxInclude: numberFixed(detail.totalTaxInclude)
                }
              }
              let rowKey = 0
              const computeProcurementDetails = procurementDetails => {
                const ret = []
                for (let detail of procurementDetails || []) {

                  //父级数据
                  const parent = {
                    ...detail, ...convertCommon(detail),
                  }
                  // mapChildren
                  let { purchaseDetails } = parent
                  if (isNotEmpty(purchaseDetails)) {
                    // 先取出第一个合并
                    const first = purchaseDetails.shift();
                    // 再处理剩余的子元素
                    purchaseDetails = purchaseDetails.map(purchase => ({
                      ...purchase, rowKey: rowKey++, parent, newRow: true,
                      totalTaxInclude: numberFixed(purchase.totalTaxInclude)
                    }))
                    // 合并第一行到父级
                    Object.assign(parent, {
                      ...first, totalTaxInclude: numberFixed(first.totalTaxInclude)
                    })
                    delete parent['parent']
                    delete parent['purchaseDetails']

                    parent['children'] = purchaseDetails
                  }
                  ret.push(parent)
                }
                return ret
              }

              this.procurementDetails = computeProcurementDetails(procurementDetails)
              this.incomeDetails = incomeDetails.map(detail => ({
                ...detail, type: computeType(detail.type),
                price: numberFixed(detail.price),
                totalTax: numberFixed(detail.totalTax),
                payAmount: numberFixed(detail.payAmount),
                totalTaxExclude: numberFixed(detail.totalTaxExclude),
                totalTaxInclude: numberFixed(detail.totalTaxInclude),
              }))

              this.attachments = attachments.map(item => ({
                ...item, isImage: isImage(item.name)
              }))
            })
            .catch(({ response }) => {
              if (response) {
                parseJSON(response)
                    .then(json => {
                      this.$message.error(json.message || "项目加载失败")
                    })
              }
              else {
                this.$message.error("项目加载失败");
              }
            })
            .finally(() => loading.close())
      },

      auditProcess(row, scope) {
        this.auditForm = {
          processId: row.id,
          processStatus: null
        }
        this.auditFormVisible = true
      },

      submitAudit() {
        this.$refs["auditForm"].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '正在审核',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })

            const form = this.auditForm

            fetch("${base}/process/audit", {
              method: 'POST', // or 'PUT'
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(form),
            }).then(checkStatus).then(data => {
              // 关闭对话框
              this.auditFormVisible = false
              this.queryTable()
              this.$message({
                showClose: true,
                message: '审核成功',
                type: 'success'
              })
            }).catch(({ response }) => {
              if (response) {
                parseJSON(response)
                    .then(json => {
                      this.$message.error(json.message || "审核失败")
                    })
              }
              else {
                this.$message.error("审核失败")
              }
            }).finally(() => loading.close())
          }
          else {
            return false;
          }
        })

      },

    }

    new Vue({
      el: '#app',
      data,
      methods,
      computed: {
        isProcurementContract() {
          return this.process.processType === 'procurement_contract'
        },
        isSaleContract() {
          return this.process.processType === 'sale_contract'
        },
      },
      mounted() {
        const processId = ${processId}
        this.loadProject(processId)
      },
      filters: {
        ellipsis(value, limit = 25) {
          if (!value) return ''
          if (value.length > limit) {
            return value.slice(0, limit) + '...'
          }
          return value
        },
        numberFormat(value) {
          return numberFixed(value)
        }
      }
    })

  </script>

</@defaultLayout.layout>
