<template>
  <div class="appVersion-container">
    <div class="head">
      <div class="head-add-btn">
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="medium"
          @click="handleShowDialog"
        >
          添加安卓包
        </el-button>
      </div>
      <div class="head-content">
        <span class="name">APP包市场：</span>
        <el-select
          v-model="selectId"
          placeholder="请选择APP市场"
          @change="handerSelectMarketId"
          class="select-content"
        >
          <el-option
            :label="item.label"
            :value="item.key"
            v-for="(item, index) of options"
            :key="index"
          ></el-option>
        </el-select>
        <span class="name">安卓包名称：</span>
        <el-input
          placeholder="请输入安卓包名称"
          suffix-icon="el-icon-search"
          v-model="appName"
          size="medium"
          class="input-with-select"
        ></el-input>
        <el-button type="primary" size="medium" @click="handleSearch">
          搜索
        </el-button>

        <el-button size="medium" @click="handleClear">清除条件</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      :height="tableConfig.height"
      style="width: 100%"
      :stripe="true"
    >
      <el-table-column
        align="center"
        v-for="(item, index) in tabColumn"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      >
        <template #default="{ row, $index }">
          <div class="" v-if="item.label == '操作'">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(row, $index)"
            >
              编辑
            </el-button>
          </div>
          <div v-else-if="item.label == '所属市场'">
            {{ formatAppShopName(row) }}
          </div>
          <div v-else-if="item.label == '开启状态'">
            <el-switch
              v-model="row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="2"
              @change="handerDisableUpdateShopApp($event, row)"
            ></el-switch>
          </div>
          <div v-else-if="item.label == '是否强制更新'">
            <el-switch
              v-model="row.is_force_update"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="2"
              @change="handerIsUpdateShopApp($event, row)"
            ></el-switch>
          </div>
          <div v-else-if="item.label == '序号'">
            {{ $index + 1 }}
          </div>
          <div v-else>
            {{ row[item.prop] }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      class="receipt-machine-dialog"
      :title="dialogTitle"
      :top="'10vh'"
      :width="'900px'"
      :visible.sync="showDialog"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="formDialog"
        class="form-dialog"
        :model="formDialog"
        :rules="formDialogRules"
        label-width="160px"
      >
        <el-form-item label="APP市场" prop="market_id">
          <el-select v-model="formDialog.market_id" placeholder="请选择APP市场">
            <el-option
              :label="item.label"
              :value="item.key"
              v-for="(item, index) of options"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="APP包名" prop="package_name">
          <el-input
            v-model="formDialog.package_name"
            placeholder="例如:com.xiaofa.shopAdmin.apk"
          ></el-input>
        </el-form-item>
        <el-form-item label="应用版本号" prop="version_key">
          <el-input
            v-model="formDialog.version_key"
            placeholder="热更新包内部整数版本号，1-10000000"
          ></el-input>
        </el-form-item>
        <el-form-item label="应用版本号名称" prop="version_name">
          <el-input
            v-model="formDialog.version_name"
            placeholder="命名规则，如：1.23.21"
          ></el-input>
        </el-form-item>
        <el-form-item label="apk 包下载地址" prop="download_apk_url">
          <div class="form-item-flex">
            <el-input
              v-model="formDialog.download_apk_url"
              placeholder="apk下载的地址"
            ></el-input>
            <el-upload
              class="upload"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-success="handleAKPUpLoadSuccess"
              :data="uploadParams"
              :before-upload="checkAPKname"
            >
              <el-button slot="trigger" size="small" type="primary">
                上传
              </el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="wgt 包下载地址" prop="download_wgt_url">
          <div class="form-item-flex">
            <el-input
              v-model="formDialog.download_wgt_url"
              placeholder="wgt 包下载地址"
            ></el-input>
            <el-upload
              class="upload"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-success="handleWGTUpLoadSuccess"
              :data="uploadParams"
              :before-upload="checkWGTname"
            >
              <el-button slot="trigger" size="small" type="primary">
                上传
              </el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="发布版本详细说明" prop="description">
          <el-input
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 20 }"
            placeholder="请输入内容"
            v-model="formDialog.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="升级包开启状态" prop="is_force_update">
          <el-switch
            v-model="formDialog.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="handerDisableUpdateShopApp($event)"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否强制更新" prop="is_force_update">
          <el-switch
            v-model="formDialog.is_force_update"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="handerIsUpdateShopApp($event)"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleCloseDialog">取 消</el-button>
        <el-button size="medium" type="primary" @click="handleSubmitForm">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <el-pagination
      background
      :current-page="params.pageNum"
      :layout="layout"
      :page-size="params.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
import {
  getShopAppVersionList,
  addShopAppVersion,
  updateShopAppVersion,
  disableUpdateShopApp,
} from '@/api/appVersion/appVersion'
import VabQuill from '@/extra/VabQuill'
import { URL } from '@/config'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/token'
export default {
  name: 'appVersion',
  components: {
    VabQuill,
  },
  data() {
    return {
      uploadParams: {
        authorization: '',
      },
      uploadUrl: URL.action, //上传网址
      showDialog: false,
      isEdit: false,
      dialogTitle: '添加APP包',
      formDialog: {
        id: '',
        market_id: '',
        package_name: '',
        version_key: '',
        version_name: '',
        download_apk_url: '',
        download_wgt_url: '',
        description: '',
        is_force_update: '',
        status: '',
      },
      vbOptions: {
        theme: 'snow',
        bounds: document.body,
        debug: 'warn',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ size: ['small', false, 'large', 'huge'] }],
              [{ color: [] }, { background: [] }],
              ['blockquote', 'code-block'],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ script: 'sub' }, { script: 'super' }],
              [{ indent: '-1' }, { indent: '+1' }],
              [{ align: [] }],
              [{ direction: 'rtl' }],
              [{ font: [] }],
              ['clean'],
              ['link', 'image', 'vab-upload-image'],
            ],
          },
        },
        placeholder: '',
        readOnly: false,
      },
      formDialogRules: {
        market_id: [
          { required: true, message: '请选择APP市场', trigger: 'change' },
        ],
        package_name: [
          { required: true, message: '请输入APP包名', trigger: 'blur' },
        ],
        version_key: [
          {
            required: true,
            message: '请输入应用版本号',
            trigger: 'blur',
          },
        ],
        version_name: [
          { required: true, message: '请输入应用版本号名称', trigger: 'blur' },
        ],
        download_apk_url: [
          { required: true, message: '请先上传apk 包', trigger: 'blur' },
        ],
        description: [
          {
            required: true,
            message: '请输入发布版本详细说明',
            trigger: 'blur',
          },
        ],
      },
      tableConfig: {
        height: window.innerHeight - 220 - 150,
      },
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      params: {
        marketId: '',
        keyword: '',
        pageNum: 1,
        pageSize: 20,
      },
      selectId: 100,
      appName: null,
      options: [
        {
          key: 1,
          label: '小米',
        },
        {
          key: 2,
          label: '华为',
        },
        {
          key: 3,
          label: '腾讯',
        },
        {
          key: 4,
          label: 'OPPO',
        },
        {
          key: 5,
          label: 'VIVO',
        },
        {
          key: 6,
          label: '三星',
        },
        {
          key: 100,
          label: '通用（不区分市场）',
        },
      ],
      tabColumn: [
        {
          prop: 'index',
          label: '序号',
          width: '51',
        },
        {
          prop: 'market_id',
          label: '所属市场',
        },
        {
          prop: 'package_name',
          label: 'APP包名字',
        },
        {
          prop: 'version_key',
          label: '应用版本号',
        },
        {
          prop: 'version_name',
          label: '应用版本号名称',
        },
        {
          prop: 'created_at',
          label: '创建时间',
        },
        {
          prop: 'updated_at',
          label: '更新时间',
        },
        {
          prop: 'updateStatus',
          label: '开启状态',
        },
        {
          prop: 'isUpdateAdd',
          label: '是否强制更新',
        },
        {
          prop: 'operation',
          label: '操作',
        },
      ],
      tableData: [
        {
          market_id: 100, // 各大安卓 APP 市场标识：1 - 小米；2 - 华为；3 - 腾讯应用市场；4 - OPPO；5 - VIVO；6 - 三星；100-通用包（不区分市场的包）；
          package_name: 'xftc', // app 包名
          version_key: 2, //热更新包内部整数版本号，1-10000000
          version_name: '1.0.2', //热更新包显示的版本号，用于标识不同的热更新版本，遵循一定命名规则，如 1.23.21
          download_apk_url: 'https://mall.gpxscs.cn/abc.apk', // apk 包下载地址
          download_wgt_url: 'https://mall.gpxscs.cn/abc.apk', // 增量包下载地址
          file_ext: 'apk', // 更新包后缀，apk, wgt 等
          release_time: '2025-03-17 00:00:01',
          description: '发布版本详细说明',
          is_force_update: 2, // 是否为强制更新，1-表示强制更新，2-表示非强制更新，
          package_size: 12332, // 热更新包的大小，以字节为单位，方便用户了解更新所需流量
          md5_checksum: '3650d648bfc19993f4408e4158b9782b', // apk 包md5加密摘要
          status: 1,
          created_by: '0',
          updated_by: '0',
          created_at: '2025-03-17 21:40:42',
          updated_at: '2025-03-17 21:58:42',
        },
      ],
    }
  },
  computed: {
    ...mapGetters({
      token: 'user/token',
    }),
  },
  created() {
    this.uploadParams.authorization = getToken()
    this.getShopAppVersionList()
  },
  methods: {
    handleShowDialog() {
      this.showDialog = true
    },
    async getShopAppVersionList() {
      this.params.marketId = this.selectId

      let res = await getShopAppVersionList(this.params)
      if (res && res.status == 200) {
        this.tableData = res.data.items
      }
    },
    handleEdit(row) {
      this.showDialog = true
      this.isEdit = true
      this.formDialog = row
    },
    handleSubmitForm() {
      this.$refs['formDialog'].validate(async (valid) => {
        if (valid) {
          let res = this.isEdit
            ? await updateShopAppVersion(this.formDialog)
            : await addShopAppVersion(this.formDialog)
          if (res && res.status == 200) {
            this.$message({
              type: 'success',
              message: this.isEdit ? '修改成功' : '添加成功!',
            })
            this.showDialog = false
            this.isEdit = false
            this.getShopAppVersionList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
            })
          }
        }
      })
    },
    handleCloseDialog() {
      this.showDialog = false
      if (this.isEdit) {
        this.formDialog = {
          market_id: '',
          package_name: '',
          version_key: '',
          version_name: '',
          download_apk_url: '',
          download_wgt_url: '',
          description: '',
          is_force_update: '',
        }
        this.isEdit = false
      }
      this.$refs['formDialog'].resetFields()
    },
    handleClear() {
      this.appName = ''

      this.params = {
        keyword: '',
        marketId: '',
        pageNum: 1,
        pageSize: 20,
      }
      this.selectId = 1
      this.getShopAppVersionList()
    },
    handleSearch() {
      this.params.keyword = this.appName

      this.getShopAppVersionList()
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum
      this.getReceiptMachineList()
    },
    handleSizeChange() {
      this.params.pageSize = pageSize
      this.getReceiptMachineList()
    },
    handlePreview(e) {},
    checkWGTname(file) {
      const isWGT = file.name.endsWith('.wgt')

      if (!isWGT) {
        this.$message.error('请上传WGT后缀的热更新包')
      }

      return isWGT
    },
    checkAPKname(file) {
      const isAPK = file.type === 'application/vnd.android.package-archive'

      if (!isAPK) {
        this.$message.error('请上传APK后缀的安卓包')
      }

      return isAPK
    },
    handleAKPUpLoadSuccess(e) {
      if (e && e.status == 200) {
        this.formDialog.download_apk_url = e.data.media_url
      }
    },
    handleWGTUpLoadSuccess(e) {
      if (e && e.status == 200) {
        this.formDialog.download_wgt_url = e.data.media_url
      }
    },
    formatAppShopName(row) {
      var name = ''

      if (row) {
        this.options.forEach((item) => {
          if (row.market_id == item.key) {
            name = item.label
          }
        })
      }

      return name
    },
    handerSelectMarketId(e) {
      this.selectId = e
    },
    async handerIsUpdateShopApp(e, row) {
      this.formDialog = row

      this.formDialog.is_force_update = e

      if (row) {
        let res = await updateShopAppVersion(this.formDialog)
        if (res && res.status == 200) {
          this.$message({
            type: 'success',
            message: '状态修改成功!',
          })

          this.getShopAppVersionList()
        }
      }
    },
    handerDisableUpdateShopApp(e, row) {
      let params = {
        id: row ? row.id : this.formDialog.id,
        status: e,
      }

      this.$confirm(`您确认${e == 1 ? '开启' : '关闭'}升级包?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await disableUpdateShopApp(params)

          if (res && res.status == 200) {
            this.$message({
              type: 'success',
              message: '状态修改成功!',
            })
            this.getShopAppVersionList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style lang="scss">
.appVersion-container {
  padding: 0 20px !important;
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: inset 0 -1px 0 #efefef;

    .head-content {
      display: flex;
      align-items: center;
      text-align: center;
      margin: 20px 0;

      .name {
        font-weight: bold;
      }

      .input-with-select {
        margin: 0 10px;
        width: 270px;
      }
    }
  }

  .select-content {
    margin-right: 20px;
  }

  .receipt-machine-dialog {
    .el-dialog {
      border: 0;
      border-radius: 6px;
      background-clip: padding-box;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .el-dialog__header {
      padding: 12px 20px;
      border-bottom: 1px solid #f2f2f2;

      .el-dialog__title {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.8);
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        top: 12px;
      }
    }

    .el-input {
      width: 63%;
    }

    .el-select {
      .el-input {
        width: 100%;
      }
    }

    .el-dialog__body {
      padding: 40px 20px;
      font-size: 12px;
      line-height: 1.5;
      color: #666;
      min-height: 108px;
      overflow-y: auto;
      max-height: 920px;
      overflow: auto;

      .form-dialog {
        min-height: 150px;
      }

      .el-input__inner {
        height: 38px;
        width: 410px;
      }
    }

    .el-dialog__footer {
      border-top: 1px solid #f2f2f2;
      padding: 10px;
    }

    .el-form-item__label {
      padding: 0 24px 0 0px;
    }

    .form-item-flex {
      display: flex;
    }
  }
}
</style>
