<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable size="small">
          <el-option v-for="dict in dict.type.source_project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="上架" value="0" />
          <el-option label="下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['generator:sourceProject:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['generator:sourceProject:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['generator:sourceProject:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['generator:sourceProject:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sourceProjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="标识" align="center" prop="slug" min-width="140" />
      <el-table-column label="分类" align="center" prop="category" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.source_project_category" :value="scope.row.category" />
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" width="100">
        <template slot-scope="scope">{{ formatPrice(scope.row.price) }}</template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="viewCount" width="100" />
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            active-text="上架"
            inactive-text="下架"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="170">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['generator:sourceProject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['generator:sourceProject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问标识" prop="slug">
              <el-input v-model="form.slug" placeholder="例如 dms-platform" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option v-for="dict in dict.type.source_project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="封面标识" prop="coverText">
              <el-input v-model="form.coverText" placeholder="例如 DMS" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="价格(元)" prop="priceYuan">
              <el-input-number v-model="form.priceYuan" :min="0" :precision="2" :step="10" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" :rows="2" placeholder="请输入项目摘要" />
        </el-form-item>
        <el-form-item label="项目描述" prop="descriptionMd">
          <el-input v-model="form.descriptionMd" type="textarea" :rows="8" placeholder="支持 Markdown" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="技术标签">
              <el-input v-model="form.tagsText" type="textarea" :rows="4" placeholder="一行一个标签" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="功能模块">
              <el-input v-model="form.modulesText" type="textarea" :rows="4" placeholder="一行一个模块" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用场景">
              <el-input v-model="form.scenesText" type="textarea" :rows="4" placeholder="一行一个场景" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="资源名称">
              <el-input v-model="form.resourceName" placeholder="源码包名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源地址">
              <el-input v-model="form.resourceUrl" placeholder="下载地址或对象存储地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="资源版本">
              <el-input v-model="form.resourceVersion" placeholder="例如 1.0.0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资源大小">
              <el-input v-model="form.resourceSize" placeholder="例如 86 MB" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序">
              <el-input-number v-model="form.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSourceProject, changeSourceProjectStatus, delSourceProject, getSourceProject, listSourceProject, updateSourceProject } from '@/api/generator/sourceProject'

export default {
  name: 'SourceProject',
  dicts: ['source_project_category'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      sourceProjectList: [],
      open: false,
      title: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        category: null,
        status: null
      },
      form: {},
      rules: {
        projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        slug: [{ required: true, message: '访问标识不能为空', trigger: 'blur' }],
        category: [{ required: true, message: '分类不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listSourceProject(this.queryParams).then(response => {
        this.sourceProjectList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        projectId: null,
        slug: '',
        projectName: '',
        category: this.defaultCategory(),
        coverText: '',
        summary: '',
        descriptionMd: '',
        priceYuan: 0,
        viewCount: 0,
        tagsText: '',
        modulesText: '',
        scenesText: '',
        resourceName: '',
        resourceUrl: '',
        resourceVersion: '1.0.0',
        resourceSize: '',
        sort: 0,
        status: '0',
        remark: ''
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增源码项目'
    },
    handleUpdate(row) {
      this.reset()
      const projectId = row.projectId || this.ids
      getSourceProject(projectId).then(response => {
        this.form = this.toForm(response.data)
        this.open = true
        this.title = '修改源码项目'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        const data = this.toPayload(this.form)
        const request = data.projectId != null ? updateSourceProject(data) : addSourceProject(data)
        request.then(() => {
          this.$modal.msgSuccess(data.projectId != null ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleStatusChange(row) {
      const text = row.status === '0' ? '上架' : '下架'
      this.$modal.confirm(`确认要${text}「${row.projectName}」吗？`).then(() => {
        return changeSourceProjectStatus(row.projectId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(`${text}成功`)
      }).catch(() => {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    handleDelete(row) {
      const projectIds = row.projectId || this.ids
      this.$modal.confirm('是否确认删除源码项目编号为 "' + projectIds + '" 的数据项？').then(function() {
        return delSourceProject(projectIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleExport() {
      this.download('generator/sourceProject/export', {
        ...this.queryParams
      }, `source_project_${new Date().getTime()}.xlsx`)
    },
    toForm(data) {
      return {
        ...data,
        priceYuan: this.centsToYuan(data.price),
        tagsText: this.toLines(data.tags),
        modulesText: this.toLines(data.modules),
        scenesText: this.toLines(data.scenes)
      }
    },
    toPayload(form) {
      return {
        ...form,
        price: this.yuanToCents(form.priceYuan),
        tags: this.fromLines(form.tagsText),
        modules: this.fromLines(form.modulesText),
        scenes: this.fromLines(form.scenesText)
      }
    },
    toLines(value) {
      if (!value) return ''
      try {
        const parsed = Array.isArray(value) ? value : JSON.parse(value)
        return Array.isArray(parsed) ? parsed.join('\n') : ''
      } catch (error) {
        return value
      }
    },
    fromLines(value) {
      return JSON.stringify(String(value || '').split(/[,，\n]/).map(item => item.trim()).filter(Boolean))
    },
    centsToYuan(value) {
      return Number(value || 0) / 100
    },
    yuanToCents(value) {
      return Math.round(Number(value || 0) * 100)
    },
    formatPrice(value) {
      const amount = this.centsToYuan(value)
      return `¥${Number.isInteger(amount) ? amount : amount.toFixed(2)}`
    },
    defaultCategory() {
      const categories = this.dict.type.source_project_category || []
      return categories.length ? categories[0].value : ''
    }
  }
}
</script>
