<template>
  <div class="edit-add-detail detail">
    <div class="edit-add-detail-new-content">
      <div class="form-content" >
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <div class="collapase-title">
                <i class="header-icon el-icon-info"></i>
                <span>私有云资源申请信息</span>
              </div>
            </template>
            <el-form ref="applyform" size="small" :model="applyform" :rules="applyformRules">
              <div class="apply-info" v-if="applyform.applyCode">
                <div class="apply-code">
                  申请编号：{{ applyform.applyCode || '' }}
                </div>
              </div>
              <el-descriptions
                class="margin-top"
                :labelStyle="{width: '150px'}"
                :column="2"
                size="medium"
                border
              >
                <el-descriptions-item label="单位名称" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    单位名称
                  </template>
                  <el-form-item prop="applyUnitName" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyUnitName"
                      placeholder="请填写单位名称"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyUnitName || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="联系人">
                  <template slot="label">
                    <i class="require-start">*</i>
                    单位联系人
                  </template>
                  <el-form-item prop="applyUnitContacts" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyUnitContacts"
                      placeholder="请填写单位联系人"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyUnitContacts || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="电话（手机）">
                  <template slot="label">
                    <i class="require-start">*</i>
                    电话（手机）
                  </template>
                  <el-form-item prop="applyUnitContactsPhone" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyUnitContactsPhone"
                      placeholder="请填写单位联系人电话（手机）"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyUnitContactsPhone || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                  <template slot="label">
                    <i class="require-start">*</i>
                    邮箱
                  </template>
                  <el-form-item prop="applyUnitContactsMail" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyUnitContactsMail"
                      placeholder="请填写邮箱"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyUnitContactsMail || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="申请时间">
                  <template slot="label">
                    <i class="require-start">*</i>
                    申请时间
                  </template>
                  <el-form-item prop="applyDate" v-if="!readOnly">
                    <el-date-picker
                      size="medium"
                      v-model="applyform.applyDate"
                      value-format="yyyy-MM-dd"
                      type="date"
                      placeholder="请选择申请时间"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyDate || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="应用系统名称" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    应用系统名称
                  </template>
                  <el-form-item prop="applyAppName" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyAppName"
                      placeholder="请填写应用系统名称"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyAppName || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="应用开发单位" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    应用开发单位
                  </template>
                  <el-form-item prop="applyAppDevelopUnit" v-if="!readOnly">
                    <el-input
                      type="textarea"
                      size="medium"
                      v-model="applyform.applyAppDevelopUnit"
                      placeholder="请填写应用开发单位"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyAppDevelopUnit || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="资源所属云平台" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    资源所属云平台
                  </template>
                  <el-form-item>
                    <el-radio-group
                      v-model="applyform.cloudType"
                      size="medium"
                      :disabled="this.applyform.status ? true : false"
                    >
                      <el-radio
                        @change="handleChangeCloudType"
                        v-for="item in cloudType"
                        :key="item.id"
                        :label="parseInt(item.value)"
                      >{{ item.name }}</el-radio
                      >
                    </el-radio-group>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="软件用途简要说明" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    软件用途简要说明
                  </template>
                  <el-form-item prop="appPurpose" v-if="!readOnly">
                    <el-input
                      type="textarea"
                      size="medium"
                      v-model="applyform.appPurpose"
                      placeholder="请填写软件用途简要说明"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.appPurpose || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="联系人">
                  <template slot="label">
                    <i class="require-start">*</i>
                    应用系统联系人
                  </template>
                  <el-form-item prop="applyAppContracts" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyAppContracts"
                      placeholder="请填写应用系统联系人"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyAppContracts || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="电话（手机）">
                  <template slot="label">
                    <i class="require-start">*</i>
                    电话（手机）
                  </template>
                  <el-form-item prop="applyAppContractsPhone" v-if="!readOnly">
                    <el-input
                      size="medium"
                      v-model="applyform.applyAppContractsPhone"
                      placeholder="请填写应用系统联系人电话（手机）"
                    ></el-input>
                  </el-form-item>
                  <div class="read-text" v-else>
                    {{ applyform.applyAppContractsPhone || '' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="应用系统规模" :span="2">
                  <template slot="label">
                    <i class="require-start">*</i>
                    应用系统规模
                  </template>
                  <el-row :gutter="10">
                    <el-col :span="6">
                      <el-form-item prop="virtualMachineNum">
                        虚拟机数量：
                        <el-input-number
                          v-if="!readOnly"
                          :min="0"
                          :controls="false"
                          v-model="applyform.virtualMachineNum"
                        ></el-input-number>
                        <span class="read-text" v-else>
                                              {{ applyform.virtualMachineNum || '' }}
                                          </span>
                        台;
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item prop="cpuNum">
                        CPU：
                        <el-input-number
                          v-if="!readOnly"
                          :min="0"
                          :controls="false"
                          @change="
                                                  (curV, oldV) =>
                                                      handleChangeApplyUse(
                                                          'cpuNum',
                                                          applyform.cloudType,
                                                          curV
                                                      )
                                              "
                          v-model="applyform.cpuNum"
                        ></el-input-number>
                        <span class="read-text" v-else>
                                              {{ applyform.cpuNum || '' }}
                                          </span>
                        核；
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item prop="memoryCapacity">
                        内存容量：
                        <el-input-number
                          v-if="!readOnly"
                          :min="0"
                          :controls="false"
                          @change="
                                                  (curV, oldV) =>
                                                      handleChangeApplyUse(
                                                          'memoryCapacity',
                                                          applyform.cloudType,
                                                          curV
                                                      )
                                              "
                          v-model="applyform.memoryCapacity"
                        ></el-input-number>
                        <span class="read-text" v-else>
                                              {{ applyform.memoryCapacity || '' }}
                                          </span>
                        G;
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item prop="dataCapacity">
                        数据量：
                        <el-input-number
                          v-if="!readOnly"
                          :min="0"
                          :controls="false"
                          @change="
                                                  (curV, oldV) =>
                                                      handleChangeApplyUse(
                                                          'storageCapacity',
                                                          applyform.cloudType,
                                                          curV
                                                      )
                                              "
                          v-model="applyform.dataCapacity"
                        ></el-input-number>
                        <span class="read-text" v-else>
                                              {{ applyform.dataCapacity || '' }}
                                          </span>
                        G；
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-descriptions-item>
                <el-descriptions-item label="附件" :span="2">
                  <el-form-item>
                    <file-upload
                      v-if="dialogVisible"
                      :dadToSon="dadToSon"
                      @sonToDad="handleFileChange"
                      :disabled="readOnly"
                    ></file-upload>
                    <span
                      class="read-text"
                      v-if="readOnly && !dadToSon.fileList.length"
                    >-</span
                    >
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item
                  label="申请单位意见"
                  v-if="id && applyform.applyUnitOpinion"
                >
                  <template slot="label">
                    <i class="require-start">*</i>
                    申请单位意见
                  </template>
                  <div
                    class="read-text"
                    v-html="applyform.applyUnitOpinion"
                  ></div>
                </el-descriptions-item>
                <el-descriptions-item
                  label="主管单位意见"
                  v-if="id && applyform.managerUnitOpinion"
                >
                  <template slot="label">
                    <i class="require-start">*</i>
                    主管单位意见
                  </template>
                  <div
                    class="read-text"
                    v-html="applyform.managerUnitOpinion"
                  ></div>
                </el-descriptions-item>
              </el-descriptions>
              <div
                class="use-section-wrapper"
                v-loading="loading"
                element-loading-background="rgba(7, 31, 48, 0.8)"
              >
                <div class="setcion-title">
                  <div class="use-section-title">分配前云资源使用情况</div>
                  <div class="use-section-title">分配后云资源使用情况</div>
                </div>
                <div class="use-section-content">
                  <div
                    class="use-type-section"
                    v-for="(
                                      item, $index
                                  ) in applyform.cloudApplyUseDetailedList"
                    :key="$index"
                  >
                    <div class="use-type-title">
                      <template v-if="item.cloudType === 1"
                      >一、XSKY 资源使用情况：</template
                      >
                      <template v-else>二、Zstack 资源使用情况</template>
                    </div>
                    <div class="use-data">
                      <el-row>
                        <el-col :span="8">
                          <div class="use-data-item">
                            CPU：共
                            <el-form-item
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              label-width="0"
                              :prop="`cloudApplyUseDetailedList.${$index}.cpuNumTotal`"
                              :rules="applyformRules.cpuNumTotal"
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeTotal(
                                                                      'cpuNum',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="item.cpuNumTotal"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.cpuNumTotal || '__' }}
                                                  </span>
                            核，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用
                            <el-form-item
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              label-width="0"
                              :prop="`cloudApplyUseDetailedList.${$index}.cpuNumUse`"
                              :rules="applyformRules.cpuNumUse"
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeUse(
                                                                      'cpuNum',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="item.cpuNumUse"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.cpuNumUse || '__' }}
                                                  </span>
                            核心，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用率
                            <el-form-item
                              label-width="0"
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              :prop="`cloudApplyUseDetailedList.${$index}.cpuNumUseRate`"
                              :rules="applyformRules.cpuNumUseRate"
                            >
                              <el-input-number
                                :min="0"
                                :max="100"
                                size="mini"
                                :precision="2"
                                :controls="false"
                                v-model="item.cpuNumUseRate"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.cpuNumUseRate || '__' }}
                                                  </span>
                            %；
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="use-data">
                      <el-row>
                        <el-col :span="8">
                          <div class="use-data-item">
                            内存：共
                            <el-form-item
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              label-width="0"
                              :prop="`cloudApplyUseDetailedList.${$index}.memoryCapacityTotal`"
                              :rules="
                                                          applyformRules.memoryCapacityTotal
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeTotal(
                                                                      'memoryCapacity',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="item.memoryCapacityTotal"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.memoryCapacityTotal || '__' }}
                                                  </span>
                            TB，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用
                            <el-form-item
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              label-width="0"
                              :prop="`cloudApplyUseDetailedList.${$index}.memoryCapacityUse`"
                              :rules="
                                                          applyformRules.memoryCapacityUse
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeUse(
                                                                      'memoryCapacity',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="item.memoryCapacityUse"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.memoryCapacityUse || '__' }}
                                                  </span>
                            TB，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用率
                            <el-form-item
                              label-width="0"
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              :prop="`cloudApplyUseDetailedList.${$index}.memoryCapacityUseRate`"
                              :rules="
                                                          applyformRules.memoryCapacityUseRate
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                :max="100"
                                size="mini"
                                :precision="2"
                                :controls="false"
                                v-model="
                                                              item.memoryCapacityUseRate
                                                          "
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{
                                item.memoryCapacityUseRate || '__'
                              }}
                                                  </span>
                            %；
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="use-data">
                      <el-row>
                        <el-col :span="8">
                          <div class="use-data-item">
                            储存：共
                            <el-form-item
                              label-width="0"
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              :prop="`cloudApplyUseDetailedList.${$index}.storageCapacityTotal`"
                              :rules="
                                                          applyformRules.storageCapacityTotal
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeTotal(
                                                                      'storageCapacity',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="
                                                              item.storageCapacityTotal
                                                          "
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{
                                item.storageCapacityTotal || '__'
                              }}
                                                  </span>
                            TB，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用
                            <el-form-item
                              label-width="0"
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              :prop="`cloudApplyUseDetailedList.${$index}.storageCapacityUse`"
                              :rules="
                                                          applyformRules.storageCapacityUse
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                size="mini"
                                :controls="false"
                                @change="
                                                              (curV, oldV) =>
                                                                  handleChangeUse(
                                                                      'storageCapacity',
                                                                      $index,
                                                                      curV
                                                                  )
                                                          "
                                v-model="item.storageCapacityUse"
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{ item.storageCapacityUse || '__' }}
                                                  </span>
                            TB，
                          </div>
                        </el-col>
                        <el-col :span="8">
                          <div class="use-data-item">
                            使用率
                            <el-form-item
                              v-if="
                                                          !readOnly &&
                                                          item.cloudType ==
                                                              applyform.cloudType
                                                      "
                              label-width="0"
                              :prop="`cloudApplyUseDetailedList.${$index}.storageCapacityUseRate`"
                              :rules="
                                                          applyformRules.storageCapacityUseRate
                                                      "
                            >
                              <el-input-number
                                :min="0"
                                :max="100"
                                :precision="2"
                                size="mini"
                                :controls="false"
                                v-model="
                                                              item.storageCapacityUseRate
                                                          "
                              />
                            </el-form-item>
                            <span class="read-text short" v-else>
                                                      {{
                                item.storageCapacityUseRate ||
                                '__'
                              }}
                                                  </span>
                            %；
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </div>
              </div>
            </el-form>
            <div class="collapse-btn-gronp" v-if="!readOnly">
              <el-button :loading="saving" type="primary" @click="handleSave"
              >保存私有云资源申请</el-button
              >
            </div>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div class="collapase-title">
                <i class="header-icon el-icon-info"></i>
                <span>私有云资源申请明细</span>
              </div>
            </template>
            <div v-if="!readOnly">
              <el-button type="primary" @click="handleAddDetail">新增</el-button
              ><el-button
              type="danger"
              @click="handleDelDetail"
              :disabled="detailDelId.length ? false : true"
            >删除</el-button
            >
            </div>
            <div class="table-wrapper">
              <el-table
                border
                stripe
                height="400"
                highlight-selection-row
                :data="detailTableData"
                v-loading="loadingDetail"
                @row-dblclick="handleEditDetail"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  align="center"
                  type="selection"
                  width="55"
                  v-if="!readOnly"
                >
                </el-table-column>
                <el-table-column
                  width="55"
                  align="center"
                  type="index"
                  label="序号"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  label="虚拟机名称"
                  prop="cloudApplyDetail.virtualMachineName"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                  align="center"
                  label="外网IP"
                  prop="cloudApplyDetail.externalIp"
                  width="140"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                  align="center"
                  label="内网IP"
                  width="140"
                  prop="cloudApplyDetail.intranetIp"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column align="center" label="规格">
                  <el-table-column
                    align="center"
                    :label="`CPU\n（核）`"
                    prop="cloudApplyDetail.cpuNum"
                    width="80"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    :label="`内存容量\n（G）`"
                    width="100"
                    prop="cloudApplyDetail.memoryCapacity"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    :label="`数据盘\n容量（G)`"
                    prop="cloudApplyDetail.sysCapacity"
                    width="100"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    :label="`数据盘\n存储容量（G）`"
                    prop="cloudApplyDetail.dataCapacity"
                    width="120"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    :label="`所属\n云平台`"
                    prop="cloudApplyDetail.cloudType"
                    width="100"
                  >
                    <template slot-scope="{row}">
                      <el-tag v-if="row.cloudApplyDetail.cloudType">
                        {{
                          getDictName(
                            'cloud_type',
                            row.cloudApplyDetail.cloudType
                          )
                        }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <!-- :label="`操作系统\n及版本`" -->
                  <el-table-column
                    align="center"
                    label="操作系统及版本"
                    show-overflow-tooltip
                    prop="cloudApplyDetail.system"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    show-overflow-tooltip
                    width="130"
                  >
                    <template slot-scope="{row}">
                      <el-button
                        size="mini"
                        type="primary"
                        @click="handleEditDetail(row)"
                        icon="el-icon-connection"
                      >
                        {{
                          pageType === 'excute'
                            ? '端口映射'
                            : '查看明细'
                        }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div class="button-style">
<!--      <el-button @click="handleClose">取 消</el-button>-->
      <el-button @click="goBack">返回</el-button>
      <el-button
        type="primary"
        @click="handleApproval('start')"
        v-if="!readOnly && pageType === 'apply'"
      >发起审核</el-button
      >
      <el-button
        type="primary"
        @click="handleApproval('agree')"
        v-if="audit && pageType === 'audit'"
      >同意</el-button
      >
      <el-button
        type="danger"
        @click="handleApproval('reject')"
        v-if="audit && pageType === 'audit'"
      >驳回</el-button
      >
      <el-button
        type="primary"
        @click="handleApproval('complete')"
        v-if="finish && pageType === 'excute'"
      >完成</el-button
      >
      <el-button type="primary" @click="handleRecord">流程日志</el-button>
      <el-button type="primary" :loading="buttonLoading" @click="applicationForm">申请表导出</el-button>
      <el-button type="danger" :loading="buttonLoading" @click="deleteRourceChange" v-if="applyform.status === 0">删除</el-button>
    </div>
    <applyDetailForm ref="applyDetailForm" @save="handleQueryApplyDetail" />
    <applyApproval ref="applyApproval" @close="handleClose" />
    <applyRecord ref="applyRecord" />
  </div>
</template>

<script>

import _ from 'lodash'
import moment from 'moment'
import {
  getApply,
  getApplyDetail,
  getCloudUseage,
  saveApply,
  deleteApplyDetail,
  downloadApply, deleteApplyList
} from '@/api/publicBasic/resourceBid'
import { getDictionaryByCode } from '@/utils/dictionary'
import applyDetailForm from './applyDetailForm.vue'
import applyApproval from './applyApproval.vue'
import applyRecord from './applyRecord.vue'
import fileUpload from '@/components/upload/fileListUpload.vue'
export default {
  name: 'ResourceDetails',
  data() {
    return {
      id:'',
      dialogVisible: false,
      selectedMenu:'',
      buttonLoading:false,
      type: '',
      activeNames: ['1'],
      cloudType: [],
      loading: false,
      applyform: {
        applyDate: moment().format('YYYY-MM-DD'),
        cloudType: null,
        cloudApplyFile: [],
        cloudApplyUseDetailedList: [
          {
            cloudType: 1,
            useType: 1,
          },
          {
            cloudType: 1,
            useType: 2,
          },
          {
            cloudType: 2,
            useType: 1,
          },
          {
            cloudType: 2,
            useType: 2,
          },
        ],
      },
      applyformRules: {
        applyUnitName: [
          {
            required: true,
            message: '请输入单位名称',
            trigger: ['blur', 'change'],
          },
        ],
        applyUnitContacts: [
          {
            required: true,
            message: '请输入单位联系人',
            trigger: ['blur', 'change'],
          },
        ],
        applyUnitContactsPhone: [
          {
            required: true,
            message: '请输入单位联系人电话',
            trigger: ['blur', 'change'],
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机格式不正确',
            trigger: ['blur', 'change'],
          },
        ],
        applyUnitContactsMail: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: ['blur', 'change'],
          },
          {
            type: 'email',
            message: '邮箱格式不正确',
            trigger: ['blur', 'change'],
          },
        ],
        applyDate: [
          {
            required: true,
            message: '请选择申请时间',
            trigger: ['blur', 'change'],
          },
        ],
        applyAppName: [
          {
            required: true,
            message: '请输入应用系统名称',
            trigger: ['blur', 'change'],
          },
        ],
        applyAppDevelopUnit: [
          {
            required: true,
            message: '请输入应用开发单位',
            trigger: ['blur', 'change'],
          },
        ],
        cloudType: [
          {
            required: true,
            message: '请选择资源所属云平台',
            trigger: ['blur', 'change'],
          },
        ],
        appPurpose: [
          {
            required: true,
            message: '请输入软件用途简要说明',
            trigger: ['blur', 'change'],
          },
        ],
        applyAppContracts: [
          {
            required: true,
            message: '请输入应用系统联系人',
            trigger: ['blur', 'change'],
          },
        ],
        applyAppContractsPhone: [
          {
            required: true,
            message: '请输入应用系统联系人电话',
            trigger: ['blur', 'change'],
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机格式不正确',
            trigger: ['blur', 'change'],
          },
        ],
        virtualMachineNum: [
          {
            required: true,
            message: '请输入虚拟机数量',
            trigger: ['blur', 'change'],
          },
        ],
        cpuNum: [
          {
            required: true,
            message: '请输入CPU核数',
            trigger: ['blur', 'change'],
          },
        ],
        memoryCapacity: [
          {
            required: true,
            message: '请输入内存容量',
            trigger: ['blur', 'change'],
          },
        ],
        dataCapacity: [
          {
            required: true,
            message: '请输入数据量',
            trigger: ['blur', 'change'],
          },
        ],
        applyUnitOpinion: [
          {
            required: true,
            message: '请输入申请单位意见',
            trigger: ['blur', 'change'],
          },
        ],
        managerUnitOpinion: [
          {
            required: true,
            message: '请输入主管单位意见',
            trigger: ['blur', 'change'],
          },
        ],
        cpuNumTotal: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateCpuNumTotal,
            trigger: ['blur', 'change'],
          },
        ],
        cpuNumUse: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateCpuNumUse,
            trigger: ['blur', 'change'],
          },
        ],
        cpuNumUseRate: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
        ],
        memoryCapacityTotal: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateCapacityTotal,
            trigger: ['blur', 'change'],
          },
        ],
        memoryCapacityUse: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateCapacityUse,
            trigger: ['blur', 'change'],
          },
        ],
        memoryCapacityUseRate: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
        ],
        storageCapacityTotal: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateStorageTotal,
            trigger: ['blur', 'change'],
          },
        ],
        storageCapacityUse: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
          {
            validator: this.validateStorageUse,
            trigger: ['blur', 'change'],
          },
        ],
        storageCapacityUseRate: [
          {
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          },
        ],
      },
      dadToSon: {
        bizPath: 'resourceApply',
        fileList: [],
      },
      saving: false,
      loadingDetail: false,
      detailTableData: [],
      detailDelId: [],
      readOnly: false,
      audit: false,
      finish: false,
      pageType: '',
      originUseData: [
        {
          cloudType: 1,
          useType: 1,
        },
        {
          cloudType: 1,
          useType: 2,
        },
        {
          cloudType: 2,
          useType: 1,
        },
        {
          cloudType: 2,
          useType: 2,
        },
      ],
    }
  },
  components: {
    applyApproval,
    applyDetailForm,
    applyRecord,
    fileUpload
  },
  created() {
    if(this.$route.query){
      this.handleOpen(this.$route.query.pageType,this.$route.query.type,this.$route.query.id)
      this.selectedMenu = this.$route.query.selectedMenu
    }
  },
  mounted() {
  },
  methods: {
    getDictionaryByCode,
    // 返回
    goBack(){
      this.$router.push({ path:'/platLayout/resourceListPage',query:{ pageType:this.pageType, selectedMenu:this.selectedMenu}});
      this.handleClose()
    },
    handleInitDict() {
      this.cloudType = this.getDictionaryByCode('zy-ssypt')
      if (this.cloudType.length) {
        this.applyform.cloudType = parseInt(this.cloudType[0].value)
      }
    },
    handleOpen(pageType, type, id) {
      this.pageType = pageType
      this.type = type
      this.handleInitDict()
      if (type === 'add') {
        this.dialogVisible = true
        this.getCloudUseage('init')
      } else if (type === 'edit') {
        this.id = id
        this.handleQueryApply()
        this.handleQueryApplyDetail()
        this.getCloudUseage()
      }
    },
    // 新增时获取云资源使用情况
    async getCloudUseage(type) {
      this.loading = true
      const { state, value} = await getCloudUseage()
      if(state){
        this.loading = false
        let tempData = []
        value.sort((a, b) => {
          return a.cloudType - b.cloudType
        })
        value.forEach((item) => {
          let newItem = {
            cloudType: item.cloudType,
            cpuNumTotal: item.cpuNumTotal,
            cpuNumUse: item.cpuNumUse,
            cpuNumUseRate: item.cpuNumUseRate,
            memoryCapacityTotal: item.memoryCapacityTotal,
            memoryCapacityUse: item.memoryCapacityUse,
            memoryCapacityUseRate: item.memoryCapacityUseRate,
            storageCapacityTotal: item.storageCapacityTotal,
            storageCapacityUse: item.storageCapacityUse,
            storageCapacityUseRate: item.storageCapacityUseRate,
          }
          tempData.push({...newItem, useType: 1})
          tempData.push({...newItem, useType: 2})
        })
        if (type === 'init') {
          this.applyform.cloudApplyUseDetailedList = tempData
        }
        this.originUseData = _.cloneDeep(tempData)
      }else{
        this.loading = false
      }
    },
    handleFileChange(data) {
      this.applyform.cloudApplyFile = data
    },
    handleRecord() {
      this.$nextTick(() => {
        this.$refs.applyRecord.handleOpen(this.applyform)
      })
    },
    handleSave() {
      this.saving = true
      this.$refs.applyform.validate(async (bool, object) => {
        if (bool) {
          let submitData = {}
          let tempData = _.cloneDeep(this.applyform)
          submitData.cloudApply = tempData
          submitData.cloudApplyUseDetailedList = tempData.cloudApplyUseDetailedList
          delete submitData.cloudApply.cloudApplyUseDetailedList
          const {state, message, value} = await saveApply(submitData)
          if (state) {
            this.saving = false
            this.id = value
            this.$message.success('云资源申请基础信息保存成功！')
          } else {
            this.saving = false
            this.$message.warning(message)
          }
        } else {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
          this.saving = false
        }
      })
    },
    async handleQueryApply() {
      const { cloudApply,cloudApplyUseDetailedList } = await getApply(this.id)
      if(cloudApply){
        this.applyform = cloudApply
      }
      if (cloudApplyUseDetailedList) {
        this.applyform.cloudApplyUseDetailedList = cloudApplyUseDetailedList
      }
      this.status = this.applyform.status
      this.readOnly = !(this.applyform.status === 0 || this.applyform.status === 20);
      this.audit = this.applyform.status === 10;
      if (this.applyform.status === 30) {
        this.finish = true
        this.activeNames = ['2']
      } else {
        this.finish = false
      }
      if (this.applyform.cloudApplyFile) {
        this.$set(
          this.dadToSon,
          'fileList',
          this.applyform.cloudApplyFile
        )
      } else {
        this.$set(this.dadToSon, 'fileList', [])
      }
      this.dialogVisible = true
    },
    // 查询资源明细
    async handleQueryApplyDetail() {
      // this.loadingDetail = true
      const res = await getApplyDetail(this.id)
      this.detailTableData = res.value || []
      // this.loadingDetail = false
    },
    handleAddDetail() {
      if (!this.id) {
        this.$message.warning('请先保存云资源申请基础信息，再添加资源申请明细！')
        return
      } else {
        this.$nextTick(() => {
          this.$refs.applyDetailForm.handleOpen(this.pageType, 'add', this.id, {
            cloudType: this.applyform.cloudType,
          })
        })
      }
    },
    handleEditDetail(row) {
      this.$nextTick(() => {
        let type = 'edit'
        if (this.readOnly) {
          type = 'readOnly'
        }
        if (this.finish && this.readOnly) {
          type = 'excute'
        }
        this.$refs.applyDetailForm.handleOpen(this.pageType, type, this.id, row)
      })
    },
    handleSelectionChange(selection) {
      this.detailDelId = selection.map((item) => item.cloudApplyDetail.id)
    },
    handleDelDetail() {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const {state, message} = deleteApplyDetail(this.id)
        if (state) {
          this.$message.success('资源申请明细删除成功！')
          this.handleQueryApplyDetail()
        } else {
          this.$message.warning(message)
        }
      })
    },
    // 审核
    handleApproval(type) {
      if (!this.id) {
        this.$message.warning('请先填写私有云资源信息，再发起审核！')
        return
      } else if (!this.detailTableData.length) {
        this.$message.warning('请先填写私有云资源申请明细，再发起审核！')
        return
      } else {
        this.$nextTick(() => {
          this.$refs.applyApproval.handleOpen(type, this.id)
        })
      }
    },
    //申请表导出
    async applicationForm(){
      await downloadApply(this.id)
      this.$message.success('导出成功')
    },
    // 删除
    deleteRourceChange(){
      this.buttonLoading = true
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const {state,message} = deleteApplyList(this.id)
        if(state){
          this.buttonLoading = false
          this.goBack()
          this.$message.success('删除成功')
        }else{
          this.buttonLoading = false
          this.$message.warning(message)
        }
      })
    },

    handleClose() {
      this.$set(this.dadToSon, 'fileList', [])
      this.activeNames = ['1']
      this.type = ''
      this.readOnly = false
      this.audit = false
      this.finish = false
      this.pageType = ''
      this.id = ''
      this.applyform = {
        applyDate: moment().format('YYYY-MM-DD'),
        cloudType: null,
        cloudApplyFile: [],
        cloudApplyUseDetailedList: [
          {
            cloudType: 1,
            useType: 1,
          },
          {
            cloudType: 1,
            useType: 2,
          },
          {
            cloudType: 2,
            useType: 1,
          },
          {
            cloudType: 2,
            useType: 2,
          },
        ],
      }
      this.detailTableData = []
      this.detailDelId = []
      this.originUseData = [] // 资源使用情况原始数据
      this.$emit('reload')
      this.dialogVisible = false
    },
    // 云平台类型变化，清空应用系统规模数据，还原分配后数据
    handleChangeCloudType() {
      delete this.applyform.cpuNum
      delete this.applyform.dataCapacity
      delete this.applyform.memoryCapacity
      this.applyform.cloudApplyUseDetailedList = _.cloneDeep(this.originUseData)
      this.$forceUpdate()
    },
    // 申请数据变化，增加使用值
    handleChangeApplyUse(dataType, cloudType, curV) {
      let changeData, originData, index
      if (cloudType === 1) {
        changeData = this.applyform.cloudApplyUseDetailedList[1]
        originData = this.originUseData[1]
        index = 1
      } else if (cloudType === 2) {
        changeData = this.applyform.cloudApplyUseDetailedList[3]
        originData = this.originUseData[3]
        index = 3
      }

      let currentValTans = curV
      // 内容、储存字段需单位换算 G -> TB 保留2位小数
      if (dataType !== 'cpuNum') {
        currentValTans = parseFloat((curV / 1024).toFixed(2))
      }

      changeData[`${dataType}Use`] = parseFloat(
        (originData[`${dataType}Use`] + currentValTans).toFixed(2)
      )

      changeData[`${dataType}UseRate`] = parseFloat(
        (
          (changeData[`${dataType}Use`] / changeData[`${dataType}Total`]) *
          100
        ).toFixed(2)
      )
      this.applyform.cloudApplyUseDetailedList.splice(index, 1, changeData)
    },
    // 总数据变化计算比率
    handleChangeTotal(dataType, index, curV) {
      let changeData = this.applyform.cloudApplyUseDetailedList[index]

      changeData[`${dataType}UseRate`] = parseFloat(
        ((changeData[`${dataType}Use`] / curV) * 100).toFixed(2)
      )

      this.applyform.cloudApplyUseDetailedList.splice(index, 1, changeData)
    },
    // 使用数据变化计算比率
    handleChangeUse(dataType, index, curV) {
      let changeData = this.applyform.cloudApplyUseDetailedList[index]

      changeData[`${dataType}UseRate`] = parseFloat(
        ((curV / changeData[`${dataType}Total`]) * 100).toFixed(2)
      )

      this.applyform.cloudApplyUseDetailedList.splice(index, 1, changeData)
    },
    // 数据字段校验
    validateCpuNumTotal(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.cpuNumUse > value) {
        callback(new Error('CPU总核心数小于使用核心数！'))
      } else {
        callback()
      }
    },
    validateCpuNumUse(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.cpuNumTotal < value) {
        callback(new Error('CPU使用核心数超过总核心数！'))
      } else {
        callback()
      }
    },
    validateCapacityTotal(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.memoryCapacityUse > value) {
        callback(new Error('内存总容量数小于使用容量！'))
      } else {
        callback()
      }
    },
    validateCapacityUse(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.memoryCapacityTotal < value) {
        callback(new Error('内存使用容量数超过总容量！'))
      } else {
        callback()
      }
    },
    validateStorageTotal(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.storageCapacityUse > value) {
        callback(new Error('储存总容量小于使用容量！'))
      } else {
        callback()
      }
    },
    validateStorageUse(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let target = this.applyform.cloudApplyUseDetailedList[index]
      if (target.storageCapacityTotal < value) {
        callback(new Error('储存使用容量超过总容量！'))
      } else {
        callback()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-collapse-item__header{
  background-color: transparent;
}
.edit-add-detail {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #0f304f;
  padding: 20px;
  box-sizing: border-box;
  .form-content {
    height: auto;
    background-color: #114066;
    padding: 10px 20px;
  }
}
.edit-add-detail-new-content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  border-radius: 10px 10px 0 0;
}
.button-style{
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #114066;
  padding: 20px;
  margin-right: 8px;
}
::v-deep .el-dialog__header{
  text-align: center;
}
.collapase-title{
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
  i{
    color: #409eff;
  }
  span{
    color: #409eff;
    font-size: 14px;
    font-weight: bold;
  }
}
::v-deep .el-collapse-item__arrow{
  color: #409eff;
}
.apply-info{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.apply-code{
  color: #fff;
  font-size: 15px;
  margin-bottom: 6px;
}
::v-deep .el-descriptions__body{
  background-color: transparent;
}
::v-deep .el-descriptions-item__label.is-bordered-label{
  background-color: transparent;
}
::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell{
  border: 1px solid #145685;
  color: #fff;
  background-color: #103b5e;
}
.collapse-btn-gronp{
  text-align: center;
  margin: 16px 0;
}
::v-deep.el-form-item--small.el-form-item{
  margin: 16px 0;
}
::v-deep.el-descriptions--medium.is-bordered .el-descriptions-item__cell{
  padding: 0 10px;
  font-size: 14px;
}
.require-start{
  color: #f56c6c;
  padding-right: 4px;
  font-size: 14px;
}
::v-deep.el-input__inner{
  background-color: transparent;
  border: 1px solid #145685;
  color: #fff;
}
::v-deep.el-select, ::v-deep.el-date-editor.el-input, ::v-deep.inputs {
  margin-right: 0;
  margin-bottom: 0;
}
.read-text{
  margin: 16px 10px;
  font-size: 14px;
}
span.read-text{
  margin: 16px 0px;
  font-size: 14px;
}
span.read-text.short{
  margin: 2px 0px;
  font-size: 14px;
}
.use-section-wrapper{
  border: 1px solid #145685;
  background-color: #103b5e;
  margin-top: 20px;
}
.setcion-title{
  display: flex;
  .use-section-title{
    flex: 1;
    color: #fff;
    border-bottom: 1px solid #145685;
    font-size: 16px;
    line-height: 14px;
    padding: 10px;
  }
  .use-section-title:nth-child(1){
    border-right: 1px solid #145685;
  }
}
.use-section-content{
  display: flex;
  flex-wrap: wrap;
  .use-type-section{
    width: 50%;
    color: #fff;
    box-sizing: border-box;
    padding:0 10px;
  }
  .use-type-section:nth-of-type(2n){
    border-left: 1px solid #145685;
  }
  .use-type-section:nth-of-type(3),.use-type-section:nth-of-type(4){
    padding-bottom: 20px;
  }
  .use-type-title{
    color: #fff;
    font-size: 14px;
    line-height: 14px;
    margin-top: 20px;
  }
  .use-data{
    color: #fff;
    font-size: 14px;
    padding-left: 28px;
    box-sizing: border-box;
    margin-top: 10px;
    .el-input-number--mini{
      width: 80px;
    }
    .use-data-item{
      display: flex;
      align-items: center;
      color: #fff;
      font-size: 14px;
      gap: 4px;
    }
  }
  ::v-deep.el-form-item--small.el-form-item{
    margin-bottom: 10px;
    margin-top: 0;
  }
}
::v-deep.el-table th.el-table__cell>.cell {
  font-size: 14px;
  white-space: pre;
}
.table-wrapper{
  margin-top: 10px;
}
::v-deep.el-dialog__footer{
  text-align: center;
}
::v-deep .el-form{
  background-color: #103b5e;
}
::v-deep .el-collapse{
  border:none;
}
::v-deep .el-collapse-item__wrap{
  background-color: #103b5e;
  border: none;
}
::v-deep .el-table thead.is-group th.el-table__cell{
  background-color: #114369 !important;
}
::v-deep .el-table th.is-leaf, .el-table td {
  border-right: 1px solid #145685 !important;
}
::v-deep.el-table--border th{
  border-bottom: 1px solid #145685 !important;
}
::v-deep.el-table td > .cell {
  font-size: 14px;
}
::v-deep.el-table--border{
  border: 1px solid #145685 !important;
}
::v-deep.el-table--border::after, ::v-deep.el-table::before {
  background-color: #145685 !important;
}
</style>
