<template>
  <div class="saas-manage card">
    <div class="search">
      <el-form :model="searchForm" size="small" :inline="true">
        <el-form-item label="">
          <el-select
            style="width: 80px"
            v-model="searchForm.timeProp"
            placeholder="请选择">
            <el-option label="创建时间" value="createTime"></el-option>
            <el-option label="过期时间" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            style="width: 360px"
            v-model="period"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:ss:mm"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="域名">
          <el-input
            size="small"
            style="width: 160px"
            v-model.trim="searchForm.domain"
            placeholder="请输入域名"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            style="width: 160px"
            clearable
            filterable
            v-model="searchForm.status"
            placeholder="请选择">
            <el-option
              v-for="(it, i) in statusList"
              :key="i"
              :label="it.value"
              :value="it.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input
            size="small"
            style="width: 160px"
            v-model="searchForm.companyName"
            placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input
            size="small"
            style="width: 160px"
            v-model="searchForm.headName"
            placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            size="small"
            icon="el-icon-plus"
            @click="addData">
            开通erp
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="deleteData">
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-wrap" v-loading="loading">
      <el-table
        ref="table"
        :data="manageData"
        border
        width="100%"
        height="100%"
        :highlight-current-row="true"
        @selection-change="handleSelectionChange"
        @row-click="rowClick"
        header-row-class-name="header-row-class-name">
        <el-table-column
          type="selection"
          width="55"
          header-align="center"
          align="center"></el-table-column>
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          header-align="center"></el-table-column>
        <el-table-column
          label="域名"
          prop="domain"
          header-align="center"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <a :href="'https://' + scope.row.domain" target="_blank">
              {{ scope.row.domain }}
            </a>
          </template>
        </el-table-column>
        <el-table-column
          label="客户名称"
          prop="companyName"
          header-align="center"
          align="center"
          width="180"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="客户编码"
          prop="userMark"
          header-align="center"
          align="center"
          width="180"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="负责人"
          prop="headName"
          header-align="center"
          align="center"
          width="100"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="联系电话"
          prop="contactPhone"
          header-align="center"
          align="center"
          width="120"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="套餐"
          prop="packages"
          header-align="center"
          align="center"
          width="120"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="资费"
          prop="charges"
          header-align="center"
          align="center"
          width="120"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="订单数"
          prop="expireTime"
          header-align="center"
          align="center"
          width="160"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.availableQuantity">
              {{ scope.row.availableQuantity }}/{{ scope.row.orderCnt }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          label="过期时间"
          prop="expireTime"
          header-align="center"
          align="center"
          width="160"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="状态"
          header-align="center"
          align="center"
          prop="statusTxt"
          width="150"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag plain :type="findStatus(scope.row.status)">
              {{ scope.row.statusTxt }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="createTime"
          header-align="center"
          align="center"
          width="160"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          width="90"
          fixed="right">
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 17px;
              ">
              <i
                class="el-icon-edit"
                style="cursor: pointer"
                title="编辑"
                @click="handleEdit(scope.row)"></i>
              <img
                src="@/assets/images/song.svg"
                style="cursor: pointer; margin: 0 6px"
                alt=""
                width="20"
                title="赠送订单"
                @click="giveOrder(scope.row)" />
              <i
                class="el-icon-tickets"
                title="操作日志"
                @click="showLog(scope.row)"
                style="cursor: pointer; color: #1565c0"></i>
              <i
                class="el-icon-position"
                v-if="scope.row.status === 9"
                title="重新开通"
                style="cursor: pointer; color: #67c23a"
                @click="reOpen(scope.row)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"></el-pagination>
    </div>
    <el-dialog
      :title="editId ? '编辑' : '新增'"
      :visible.sync="addVisible"
      :close-on-click-modal="false"
      width="700px">
      <el-form
        :model="editForm"
        size="small"
        ref="form"
        :inline="true"
        label-width="110px"
        label-position="right">
        <el-form-item
          label="域名"
          prop="domain"
          :rules="[{ required: true, message: '请输入域名' }]">
          <el-input
            style="width: 200px"
            v-model.trim="editForm.domain"
            size="small"
            :disabled="!!editId"
            clearable
            @change="onChange"
            placeholder="请输入域名">
            <template slot="append">{{ baseDomain }}</template>
          </el-input>
        </el-form-item>

        <el-form-item
          label="公司名称"
          prop="companyName"
          :rules="[{ required: true, message: '请输入公司名称' }]">
          <el-input
            style="width: 200px"
            v-model="editForm.companyName"
            size="small"
            placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item
          label="套餐"
          prop="packages"
          :rules="[{ required: true, message: '请选择套餐' }]">
          <el-select
            style="width: 200px"
            v-model="editForm.packages"
            size="small"
            @change="changeCharges"
            placeholder="请选择套餐">
            <el-option
              v-for="item in paymentPackages"
              :key="item.id"
              :value="item.key"
              :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="负责人"
          prop="headName"
          :rules="[{ required: true, message: '请输入负责人' }]">
          <el-input
            style="width: 200px"
            v-model="editForm.headName"
            size="small"
            placeholder="负责人" />
        </el-form-item>
        <el-form-item
          label="联系电话"
          prop="contactPhone"
          :rules="[
            { required: true, message: '请输入联系电话' },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的电话号码格式',
              trigger: 'blur'
            }
          ]">
          <el-input
            style="width: 200px"
            v-model="editForm.contactPhone"
            size="small"
            placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item
          label="资费"
          prop="charges"
          :rules="[{ required: true, message: '请输入资费' }]">
          <el-input
            disabled
            style="width: 200px"
            v-model="editForm.charges"
            size="small"
            placeholder="请输入资费" />
        </el-form-item>
        <el-form-item
          label="过期时间"
          prop="expireTime"
          :rules="[{ required: true, message: '请选择过期时间' }]">
          <el-date-picker
            style="width: 200px"
            v-model="editForm.expireTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addVisible = false" size="small">取消</el-button>
        <el-button @click="save" type="primary" size="small">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="赠送订单"
      :visible.sync="giftOrderVisible"
      :close-on-click-modal="false"
      width="400px">
      <el-form
        :model="giftOrderForm"
        ref="giftOrderForm"
        label-width="100px"
        label-position="right">
        <el-form-item
          label="订单数量"
          prop="quantity"
          :rules="[
            { required: true, message: '请输入订单数量' },
            { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数' }
          ]">
          <el-input
            style="width: 200px"
            v-model="giftOrderForm.quantity"
            size="small"
            placeholder="请输入订单数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            class="remark_input"
            style="width: 200px"
            v-model="giftOrderForm.remark"
            size="small"
            type="textarea"
            rows="4"
            maxlength="100"
            show-word-limit
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="giftOrderVisible = false" size="small">
          取消
        </el-button>
        <el-button @click="submitGiftOrder" type="primary" size="small">
          确定
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="操作日志"
      :close-on-click-modal="false"
      :visible.sync="noteVisible"
      width="700px">
      <ul style="color: #333; font-size: 12px; height: 600px; overflow: auto">
        <li v-for="(item, index) in logList" :key="index" style="height: 30px">
          ({{ index + 1 }})、{{ item.operateName + '：' + item.msg }}
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
import {
  getManageData,
  getStatusSelect,
  addManageData,
  updateManageData,
  getDataById,
  deleteData,
  reOpenErp,
  addGiftOrders,
  getLogById
} from '@/common/api/manage/index'

export default {
  name: 'saasManage',
  data() {
    return {
      noteVisible: false,
      logList: [],
      statusColor: [
        {
          key: 1,
          value: 'success'
        },
        {
          key: 2,
          value: 'warning'
        },
        {
          key: 3,
          value: 'info'
        },
        {
          key: 4,
          value: 'info'
        },
        {
          key: 9,
          value: 'danger'
        }
      ],
      paymentPackages: [
        {
          id: 0,
          cny: 'CNY',
          price: 10,
          name: '内测版',
          key: 'INNERBATE',
          o: 0.2,
          oName: '0',
          orders: 10000
        },
        {
          id: 1,
          cny: 'CNY',
          price: 10000,
          name: '基础版',
          key: 'PAYBASE',
          o: 0.2,
          oName: '0.2元/单',
          orders: 50000
        },
        {
          id: 2,
          cny: 'CNY',
          price: 30000,
          name: '进阶版',
          key: 'PAYADVANCED',
          o: 0.16,
          oName: '0.16元/单',
          orders: 187500
        },
        {
          id: 3,
          cny: 'CNY',
          price: 9800,
          p: 9800,
          name: '尊享版',
          key: 'PAYXVCVT',
          month: 1,
          oName: '9800元/月',
          m: '按月收费'
        },
        {
          id: 4,
          cny: 'CNY',
          price: 29800,
          p: 29800,
          name: '至尊版',
          key: 'PAYULTIMATE',
          month: 1,
          oName: '29800元/月',
          m: '按月收费'
        }
      ],
      period: [],
      manageData: [],
      searchForm: {},
      editId: undefined,
      editForm: {
        domain: ''
      },
      total: 0,
      pageSize: 50,
      currentPage: 1,
      addVisible: false,
      selection: [],
      statusList: [],
      cloneEditForm: {},
      loading: false,
      baseDomain: '.jomalls.com',
      giftOrderVisible: false,
      giftOrderForm: {
        quantity: '',
        remark: ''
      },
      currentRow: {}
    }
  },
  async created() {
    this.cloneEditForm = JSON.parse(JSON.stringify(this.editForm))
    await this.getList()
    await this.getStatusList()
  },
  methods: {
    async showLog(item) {
      try {
        const res = await getLogById(item.id)
        if (res.code !== 200) return
        if (res.data.length > 0) {
          this.logList = res.data
          this.noteVisible = true
        } else {
          this.$message.warning('暂无数据')
        }
      } catch (e) {
        console.error(e)
      }
    },
    findStatus(status) {
      const item = this.statusColor.find((el) => el.key === status)
      return item ? item.value : ''
    },
    async getStatusList() {
      const { data } = await getStatusSelect()
      this.statusList = data
    },
    changeCharges(v) {
      if (!v) return
      const charges = this.paymentPackages.find((item) => item.key === v)
      if (charges) {
        this.$set(this.editForm, 'charges', charges.oName)
      }
    },
    onChange(e) {
      this.$set(this.editForm, 'apiName', e)
      this.$set(this.editForm, 'databaseName', e)
    },
    async getList() {
      this.loading = true
      try {
        const res = await getManageData(
          {
            ...this.searchForm,
            beginDate: this.period && this.period[0],
            endDate: this.period && this.period[1]
          },
          this.currentPage,
          this.pageSize
        )
        this.manageData = res.data.records
        this.total = res.data.total
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    search() {
      this.getList()
    },
    addData() {
      this.addVisible = true
      this.editId = undefined
      this.editForm = JSON.parse(JSON.stringify(this.cloneEditForm))
      this.baseDomain = '.jomalls.com'
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async reOpen(row) {
      try {
        await this.$confirm('确认重新开通？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }
      try {
        const res = await reOpenErp(row.id)
        if (res.code === 200) {
          this.$message.success(res.message)
          await this.getList()
        }
      } catch (e) {
        console.error(e)
      }
    },
    giveOrder(row) {
      this.currentRow = row
      this.giftOrderVisible = true

      // 表单赋值，否则就清空
      // if (row.quantity || row.remark) {
      //   this.giftOrderForm = {
      //     quantity: row.quantity || '',
      //     remark: row.remark || ''
      //   }
      // } else {
      this.giftOrderForm = {
        quantity: '',
        remark: ''
      }
      // }
      this.$nextTick(() => {
        this.$refs.giftOrderForm.clearValidate()
      })
    },
    submitGiftOrder() {
      this.$refs.giftOrderForm.validate(async (valid) => {
        if (valid) {
          const res = await addGiftOrders({
            apiName: this.currentRow.apiName,
            giftOrderQuantity: Number(this.giftOrderForm.quantity),
            remark: this.giftOrderForm.remark
          })
          if (res.code === 200) {
            this.$message.success(res.message)
            this.getList()
            this.giftOrderVisible = false
          }
        }
      })
    },
    async handleEdit(row) {
      this.editId = row.id
      const l = this.$loading({
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        const res = await getDataById(row.id)
        const parts = /^(.*)(\.(([^.]+)\.([^.]+)))$/.exec(res.data.domain)
        if (parts) {
          const name = parts[1]
          const tld = '.' + parts[3]
          res.data.domain = name
          this.baseDomain = tld
        }
        this.editForm = res.data
      } catch (e) {
        this.$message.error(e)
      } finally {
        l.close()
      }
      this.addVisible = true
    },
    async save() {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      const l = this.$loading({
        background: 'rgba(0, 0, 0, 0.3)'
      })
      let databaseName
      if (!this.editId) {
        databaseName = 'saas_' + this.editForm.databaseName
      }
      const domain = this.editForm.domain + this.baseDomain
      try {
        if (this.editId) {
          const res = await updateManageData({
            ...this.editForm,
            domain: domain,
            databaseName: databaseName
          })
          if (res.code === 200) {
            this.$message.success(res.message)
            this.getList()
            this.addVisible = false
          }
        } else {
          const res = await addManageData({
            ...this.editForm,
            domain: domain,
            databaseName: databaseName
          })
          if (res.code === 200) {
            this.$message.success(res.message)
            this.getList()
            this.addVisible = false
          }
        }
      } catch (e) {
        this.$message.warning(e)
      } finally {
        l.close()
      }
    },
    async deleteData() {
      if (this.selection.length === 0) {
        this.$message.error('请至少选择一条记录')
        return
      }
      let ids = []
      ids = this.selection.map((item) => item.id)
      ids = ids.join()
      const l = this.$loading({
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        await deleteData(ids)
        this.getList()
      } catch (e) {
        console.error(e)
      } finally {
        l.close()
      }
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    onCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getList()
    },
    sizeChange(pageSize) {
      this.pageSize = pageSize
      this.getList()
    },
    rowClick(row) {
      if (this.selection.length === 1 && this.selection[0] === row) {
        this.selection = []
        this.$refs.table.clearSelection()
      } else {
        this.selection = [row]
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(row, true)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.saas-manage {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .remark_input {
    ::v-deep(.el-input__count) {
      background: transparent;
    }
  }
  &::v-deep {
    .el-table .el-table__cell {
      padding: 6px 0;
    }

    .el-input__inner {
      padding: 0 4px;
    }

    .el-input--small .el-input__inner {
      height: 30px;
      line-height: 30px;
    }

    .el-icon-time:before {
      content: '';
    }

    .el-dialog__footer {
      text-align: center;

      .el-button--small {
        padding: 9px 50px;
      }
    }

    .el-dialog__body {
      padding: 10px 20px;
    }

    .el-icon-edit:before {
      color: #ff9800;
      font-weight: bold;
    }

    .el-range-editor--small .el-range-separator {
      line-height: 31px;
    }

    .header-row-class-name th {
      background-color: #f8f8f9;
    }

    .el-input-group__append {
      padding-left: 0;
    }
  }
}

.search {
  background: #fff;
}

.table-wrap {
  background: #fff;
  flex: 1;
  overflow: hidden;
}
</style>
