<template>
  <section class="AppDeployWxmp">
    <ai-list>
      <ai-title slot="title" title="小程序部署发布" isShowBottomBorder/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" @click="handleSyncData">同步数据</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="搜索项目/系统/appId/上传版本" v-model="search.name" clearable
                      @change="page.current=1,getTableData()"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="page.total" :current.sync="page.current" :size.sync="page.size"
                  @getList="getTableData" :col-configs="colConfigs" :dict="dict">
          <el-table-column type="expand" slot="expand">
            <template slot-scope="{row}">
              <ai-wrapper>
                <ai-info-item labelWidth="200px" v-for="op in desConfigs" :key="op.prop" :value="row.dvcpConfig[op.prop]"
                              v-bind="op"/>
              </ai-wrapper>
            </template>
          </el-table-column>
          <el-table-column slot="process" label="打包进度">
            <template slot-scope="{row}">
              <span v-if="row.count==0" v-text="getProcessMsg(row)"/>
              <el-progress v-else :percentage="row.count"/>
            </template>
          </el-table-column>
          <el-table-column slot="options" label="操作" fixed="right" align="center" width="300">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="handleZip(row)" v-if="row.count==0">打包</el-button>
              <el-button type="text" @click="handleCancelZip(row)" v-else>停止</el-button>
              <el-button type="text" v-if="/^打包时间/.test(row.error)" @click="handleDownload(row)">下载</el-button>
              <el-button v-if="row.target" type="text" @click="handleUpdateSystem(row)">更新部署</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog :visible.sync="dialog" title="部署设置" width="600px" @close="form={}" @onConfirm="submit">
      <el-form ref="DialogForm" :model="form" size="small" label-width="120px" :rules="rules">
        <el-form-item label="项目/系统" prop="name">
          {{ form.name }}(appid:<b v-text="form.appid"/>)
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <ai-select v-model="form.version" :instance="instance" action="/node/custom/list?type=mp" :prop="{label:'name'}"
                     @select="v=>form.versionName=v.name"/>
        </el-form-item>
        <el-form-item label="小程序上传私钥" prop="privateKey">
          <el-input v-model="form.privateKey" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="项目地址" prop="projectPath">
          <el-input v-model="form.projectPath" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="npm构建脚本" prop="npmScript">
          <el-input v-model="form.npmScript" clearable placeholder="请输入"/>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from "vuex";

export default {
  name: "AppDeployWxmp",
  label: "小程序发布",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    ...mapState(['user']),
    desConfigs() {
      let isLine = true
      return [
        {prop: "corp_id", label: "企业微信corpId"},
        {prop: "corp_address_book_secret", label: "企业微信通讯录SECRET", width: 200},
        {prop: "corp_agent_id", label: "企业微信AGENTID", width: 150},
        {prop: "corp_secret", label: "企业微信SECRET", isLine},
        {prop: "corp_token", label: "企业微信TOKEN", width: 150},
        {prop: "corp_aeskey", label: "企业微信AESKEY", width: 150},
        {prop: "miniapp_secret", label: "小程序SECRET", width: 150},
        {prop: "area_id", label: "地区编码", width: 150, isLine},
        {prop: "lat", label: "纬度", width: 100},
        {prop: "lng", label: "经度", width: 100},
        {prop: "address", label: "中心点", width: 100, isLine},
        {prop: "web_url", label: "管理端地址", width: 100},
        {prop: "dvcp_url", label: "企微端地址", width: 100},
      ]
    },
  },
  data() {
    return {
      search: {name: ""},
      page: {current: 1, size: 10, total: 0},
      tableData: [],
      colConfigs: [
        {slot: "expand"},
        {label: "项目/系统名称", prop: "name", width: 300},
        {label: "appId", prop: "appid", width: 180},
        {label: "管理后台", prop: "webUrl"},
        {label: "上传版本", render: (h, {row}) => h('p', row.versionName || row.version)},
        {slot: "process"},
        {slot: "options"}
      ],
      dialog: false,
      form: {},
      rules: {
        // privateKey: {required: true, message: "请输入 小程序上传私钥"},
        // projectPath: {required: true, message: "请输入 项目地址"},
        version: {required: true, message: "请选择 定制方案"},
      },
      timer: {}
    }
  },
  methods: {
    handleSyncData() {
      this.instance.post("/node/wxmp/sync").then(this.getTableData)
    },
    getTableData() {
      this.instance.post("/node/wxmp/list", null, {
        params: {...this.page, ...this.search}
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data?.records.map(e => {
            e.dvcpConfig = JSON.parse(e.dvcpConfig)
            return {...e, count: 0}
          })
          this.page.total = res.data.total
        }
      })
    },
    handleDownload(row) {
      let {id} = row
      this.instance.post("/node/wxmp/download", null, {
        params: {id},
        responseType: "blob"
      }).then(res => {
        if (res?.code == 1) {
          this.$message.error(res.err)
        } else {
          const link = document.createElement('a')
          let blob = new Blob([res], {type: 'application/zip'})
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', row.name + '.zip')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      })
    },
    handleZip(row) {
      let {appid, version, id} = row
      if (!version) return this.$message.error("请先维护要上传的版本!")
      appid && this.instance.post("/node/wxmp/getZip", null, {
        params: {appid, id}
      }).then(res => {
        if (res?.code == 0) {
          row.count = 1
          this.timer[id] = setInterval(() => {
            if (row.count >= 100) {
              clearInterval(this.timer[id])
              this.$message.error("打包失败!")
            } else if (row.count <= 25) {
              row.count++
            } else this.handleConfirmZip(row).then(v => {
              if (v.error) {
                clearInterval(this.timer[id])
                row.error = v.error
                row.count = 0
              } else row.count++
            })
          }, 3000)
        }
      }).catch(() => this.$message.error("打包失败!"))
    },
    handleCancelZip(row) {
      clearInterval(this.timer[row.id])
      row.count = 0
    },
    handleUpdateSystem(row) {
      let {appid} = row
      return this.instance.post("/node/wxmp/updateSystem", null, {
        params: {appid}
      }).then(res => {
        if (res?.code == 0) {

        }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialog = true
    },
    submit() {
      this.$refs.DialogForm.validate(v => {
        if (v) {
          this.instance.post("/node/wxmp/addOrUpdate", this.form).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功")
              this.getTableData()
              this.dialog = false
            }
          })
        }
      })
    },
    handleDelete(ids) {
      this.$confirm("是否要删除该项目/系统?").then(() => {
        this.instance.post("/node/autodeploy/delete", null, {
          params: {ids}
        }).then(res => {
          if (res?.code == 0) {
            this.$message.success("删除成功")
            this.getTableData()
          }
        })
      }).catch(() => 0)
    },
    handleConfirmZip(row) {
      let {appid, pid} = row
      return this.instance.post("/node/wxmp/confirmZip", null, {
        params: {appid, pid}
      }).then(res => {
        if (res?.code == 0) return res.data
      })
    },
    getProcessMsg(row) {
      return row.error || `暂无打包`
    }
  },
  created() {
    this.getTableData()
  },
  beforeDestroy() {
    Object.values(this.timer).map(t => clearInterval(t))
  }
}
</script>

<style lang="scss" scoped>
.AppDeployWxmp {
  height: 100%;
}
</style>
