<template>
  <div>
    <a-card :bordered="false">
      <a-row>
        <a-col :sm="8" :xs="24">
          <info :bordered="true" :value="`${this.coll.filesNum}个文件`" title="所有文件数量"/>
        </a-col>
        <a-col :sm="8" :xs="24">
          <info :bordered="true" :value="`${this.coll.weekFiles}个文件`" title="本周上传文件数量"/>
        </a-col>
        <a-col :sm="8" :xs="24">
          <info :value="`${this.coll.fileSize} mb`" title="储存用量"/>
        </a-col>
      </a-row>
    </a-card>
    <a-card
      :bordered="false"
      style="margin-top: 24px"
      title="文件仓库列表">
      <div v-show="!loading" class="operate">
        <a-button icon="plus" style="width: 100%" type="dashed" @click="add_edit">添加</a-button>
      </div>
      <a-list :loading="loading" size="large">
        <a-list-item v-for="(item, index) in data" :key="index">
          <a-list-item-meta :description="item.f_describe">
            <a-avatar
              slot="avatar"
              :icon="item.f_stock_type ==='oss'?'cloud-server':'hdd'"
              :style="{ backgroundColor: '#1890ff', color: item.progress?'rgba(255,255,255)':'rgba(255,255,255, 0.50)' }"
              shape="square"
              size="large"
            />
            <a slot="title">{{ item.f_name }}</a>
          </a-list-item-meta>
          <div slot="actions">
            <a-button
              block
              type="link"
              @click="add_edit(item)">
              编辑
            </a-button>
          </div>
          <div
            class="
              list-content">
            <div class="list-content-item" style="width: 150px">
              <span style="color:rgba(0,0,0, 0.65)">仓库类型</span>
              <p>{{ item.f_stock_type }}</p>
            </div>
            <div class="list-content-item" style="width: 150px">
              <span style="color:rgba(0,0,0, 0.65)">根目录</span>
              <p>{{ item.f_root_path }}{{ item.f_alias }}</p>
            </div>
            <div class="list-content-item" style="width: 150px">
              <span style="color:rgba(0,0,0, 0.65)">文件大小</span>
              <p>{{ item.file_size }} mb</p>
            </div>
            <div class="list-content-item">
              <a-progress :percent="Number(item.progress.toFixed(2))" style="width: 180px"/>
            </div>
          </div>
        </a-list-item>
      </a-list>
      <a-modal
        :maskClosable="false"
        :title="form.id ? '修改仓库信息':'新增仓库信息'"
        :visible="visible"
        @cancel="handleCancel"
        @ok="handleOk"
      >
        <a-form-model
          ref="formModel"
          :model="form"
          :rules="itemRules"
          layout="vertical">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="仓库名称" prop="f_name">
                <a-input v-model="form.f_name" placeholder="仓库名称"/>
              </a-form-model-item>
            </a-col>
            <!--            <a-col :span="12">-->
            <!--              <a-form-model-item label="仓库别名" prop="f_alias">-->
            <!--                <a-input placeholder="仓库名称" v-model="form.f_alias"/>-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <a-col :span="12">
              <a-form-model-item
                label="仓库类型"
                prop="f_stock_type">
                <a-select v-model="form.f_stock_type">
                  <a-select-option key="server">服务器</a-select-option>
                  <a-select-option key="oss">对象存储</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">

              <a-form-model-item
                label="根目录"
                prop="f_alias">
                <a-input v-model="form.f_alias" placeholder="根目录" @blur="aliasBlur">
                  <!--     TODO 先这么写单独文件服务出来后根据文件地址服务写        -->
                  <a-select slot="addonBefore" v-model="form.f_root_path" default-value="D:\nginx-resource\" style="width: 13rem">
                    <a-select-option value="D:\nginx-resource\">
                      D:\nginx-resource\
                    </a-select-option>
                  </a-select>
                </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row v-for="(item,index) in form.f_lower_path_json" :key="index" :gutter="24">
            <a-col :span="12">
              <a-form-model-item :label="`扩展路径 ${index+1}`">
                <a-popconfirm
                  :visible="pop_visible[index]"
                  cancel-text="取消"
                  ok-text="确认"
                  placement="topLeft"
                  title="是否要删除此条扩展路径"
                  @cancel="refresh_pop()"
                  @confirm="executeDelLower(index)"
                >
                  <a-icon slot="icon" style="color: red" type="question-circle-o"/>
                  <a-input
                    v-model="form.f_lower_path_json[index].value"
                    placeholder="扩展路径"
                    @keydown.delete="delLower(index)"
                    @keydown.enter="delLower(index,'enter')"/>
                </a-popconfirm>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="`扩展路径 ${index+1} 描述`">
                <a-input v-model="form.f_lower_path_json[index].label" placeholder="扩展路径描述"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-item>
            <a-button style="width: 100%" type="dashed" @click="addLower">
              <a-icon type="plus"/>
              添加一个扩展路径
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-input v-model="form.f_describe" placeholder="仓库描述"/>
          </a-form-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import Info from './Info'
import { post } from '@vue2-client/services/api/restTools'

export default {
  name: 'FileManager',
  components: { Info },
  data () {
    return {
      data: [],
      visible: false,
      rules: '',
      coll: {
        filesNum: 0,
        fileSize: 0,
        weekFiles: 0
      },
      loading: false,
      form: {
        f_name: '',
        f_alias: '',
        f_describe: '',
        f_stock_type: 'server',
        f_root_path: '',
        f_lower_path_json: [],
        f_lower_path_vec: []
      },
      pop_visible: [],
      itemRules: {
        f_name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        f_alias: [{ required: true, message: '仓库根目录路径不正确', pattern: /^((?:[a-zA-Z0-9]+\\?)*)$/, trigger: 'blur' }],
        f_stock_type: [{ required: true, message: '请选择仓库类型', trigger: 'blur' }],
      },
    }
  },
  mounted () {
    this.getStockList()
  },
  methods: {
    // 请求仓库列表
    getStockList () {
      this.loading = true
      // 请求仓库列表
      post('/api/af-system/logic/getFilesStock', {}).then(res => {
        this.data = res.sort((a, b) => a.progress - b.progress)
        // 请求仓库列表
        post('/api/af-system/logic/getFilesColl', {}).then(res => {
          this.coll = res
          this.loading = false
        })
      })
      .catch(e => {
      })
    },
    // 添加扩展路径
    addLower () {
      this.form.f_lower_path_json.push({ label: '', value: '' })
      this.refresh_pop()
    },
    delLower (index, type) {
      if (this.pop_visible[index]) {
        // 如果提示框打开则直接删除
        if (type === 'enter') {
          this.executeDelLower(index)
        }
      } else {
        // 否则提示
        if (!this.form.f_lower_path_json[index].value) {
          this.pop_visible[index] = true
          this.pop_visible = JSON.parse(JSON.stringify(this.pop_visible))
        }
      }
    },
    // 删除扩展路径
    executeDelLower (index) {
      if (!this.form.f_lower_path_json[index].value) {
        this.form.f_lower_path_json.splice(index, 1)
      }
      this.refresh_pop()
    },
    // 刷新 控制删除提示框的 数组
    refresh_pop () {
      this.pop_visible = Array(this.form.f_lower_path_json.length).fill(false)
    },
    add_edit (item = {}) {
      // todo 添加或者修改
      this.form = Object.assign({
        f_name: '',
        f_alias: '',
        f_describe: '',
        f_stock_type: 'server',
        f_root_path: '',
        f_lower_path_json: [],
        f_lower_path_vec: []
      }, item)
      this.visible = true
    },
    handleOk () {
      this.$refs.formModel.validate(valid => {
        if (valid) {
          const countLower = this.form.f_lower_path_json.filter(item => !/^[A-Za-z]+$/.test(item.value))
          if (countLower.length > 0) {
            this.$message.error(`${countLower.map(item => item.label).join(';')},输入不合法,扩展路径应仅有大小写字母构成`)
            return
          }
          const server = this.form.f_stock_type === 'server' && /^[a-zA-Z]:\\(?:\w+\\?)*$/.test(this.form.f_root_path)
          const cloud = this.form.f_stock_type === 'oss' && /^\/(?:[^/]+\/)*$/.test(this.form.f_root_path)
          if (!(server || cloud)) {
            this.$message.error(`${this.form.f_stock_type === 'server' ? '根目录路径不正确，示例：E:\\demo' : '根目录路径不正确，示例：/img-1251014762/blog'}`)
            return
          }
          this.submitStock()
        }
      })
    },
    submitStock () {
      // 保存仓库信息
      post('/api/af-system/entity/t_files_manager', this.form).then(res => {
        this.$message.success('提交成功')
        this.visible = false
        this.getStockList()
      }).catch(e => {
      })
      // todo
    },
    handleCancel () {
      this.visible = !this.visible
      this.$refs.formModel.resetFields()
    },
    aliasBlur () {
      if (this.form.f_alias.substr(this.form.f_alias.length - 1, this.form.f_alias.length) === '\\') {
        this.form.f_alias = this.form.f_alias.substr(0, this.form.f_alias.length - 1)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}

.list-content-item {
  color: rgba(0, 0, 0, .45);
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  margin-left: 40px;

  span {
    line-height: 20px;
  }

  p {
    margin-top: 4px;
    margin-bottom: 0;
    line-height: 22px;
  }
}
</style>
