<template>
  <div class="wraper">
    <div class="page_right">
      <el-form
        :model="searchForm"
        size="mini"
        v-enter-submit="getTableList"
        :inline="true"
        ref="form"
        class="search_form">
        <el-form-item label="公司名称">
          <el-input
            style="width: 130px"
            v-model="searchForm.companyName"
            placeholder="请输入公司名称"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="业务对接人">
          <el-input
            style="width: 130px"
            v-model="searchForm.contactUserName"
            placeholder="请输入业务对接人"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="ERP服务">
          <el-select
            v-model="searchForm.erpServiceStatus"
            style="width: 130px"
            value-key=""
            placeholder="请选择服务状态"
            clearable
            filterable>
            <el-option
              v-for="item in serviceStatusLists"
              :key="item.code"
              :label="item.remark"
              :value="item.code">
              <span :style="{ color: item.color, fontWeight: 600 }">
                {{ item.remark }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="域名">
          <el-input
            style="width: 130px"
            v-model="searchForm.domain"
            placeholder="请输入域名"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="客户编码">
          <el-input
            style="width: 130px"
            v-model="searchForm.erpUserMark"
            placeholder="请输入客户编码"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="客户运营">
          <el-select
            v-model="searchForm.operationUserId"
            placeholder="请选择客户运营"
            style="width: 130px"
            clearable
            filterable>
            <el-option
              v-for="item in userLists"
              :key="item.id"
              :label="item.realName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label>
          <el-button @click="getTableList()" type="primary" size="mini">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="mini" @click="addCustomerInfo">
            新增客户
          </el-button>
        </el-form-item>
      </el-form>
      <div class="table-wrap" v-loading="loading">
        <table-view
          :tableColumns="tableColumns"
          :sourceData="sourceData"
          @selectionChange="handleSelectionChange"
          :selection="true"></table-view>
      </div>
      <div class="pagination">
        <el-pagination
          layout="sizes, total, prev, pager, next, jumper"
          background
          :total="centerPageOptions.total"
          :page-size="centerPageOptions.pageSize"
          :current-page="centerPageOptions.currentPage"
          @size-change="sizeChange"
          @current-change="onCurrentChange"></el-pagination>
      </div>
    </div>
    <editCustmerDialog
      :editDialog.sync="editDialog"
      @onSubmit="onSubmit"
      :editForm="editForm"
      :userLists="userLists"
      :commandTitle="commandTitle"
      :erpStatus="erpStatus"
      ref="customerRef" />
    <el-dialog
      title="操作日志"
      :close-on-click-modal="false"
      :visible.sync="logVisible"
      width="700px">
      <ul style="color: #333; font-size: 14px; height: 600px; overflow: auto">
        <li v-for="(item, index) in logList" :key="index">
          {{ index + 1 }}、{{ item.createTime + '：' + item.description }}
        </li>
      </ul>
    </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: /^(0|-[1-9]\d*|[1-9]\d*)$/, message: '请输入整数' }
          ]">
          <el-input
            style="width: 200px"
            v-model="giftOrderForm.quantity"
            size="small"
            clearable
            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"
          :loading="submitLoading">
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableView from '@/common/components/base/tableView.vue'
import pagination from '../../mixins/pagination'
import editCustmerDialog from './editCustmerDialog.vue'
import { get, post, remove } from '@/common/api/axios'
import { mapState } from 'vuex'
import { addGiftOrders } from '@/common/api/manage/index'
export default {
  name: 'user_jm_management',
  mixins: [pagination],
  components: {
    tableView,
    editCustmerDialog
  },
  data() {
    return {
      submitLoading: false,
      userLists: [],
      giftOrderForm: {
        quantity: '',
        remark: ''
      },
      giftRules: {
        orderQuantity: [
          { required: true, message: '请输入订单数量', trigger: 'blur' }
        ]
      },
      logVisible: false,
      giftOrderVisible: false,
      logList: [],
      searchForm: {
        companyName: '',
        contactUserName: '',
        erpServiceStatus: '',
        domain: '',
        erpUserMark: ''
      },
      serviceStatusLists: [],
      sourceData: [],
      centerPageOptions: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selections: [],
      editDialog: false,
      commandTitle: 'add',
      editForm: {
        companyName: '',
        industry: '',
        registeredAddress: '',
        officeAddress: '',
        contactUserName: '',
        contactUserTitle: '',
        contactUserPhone: '',
        contactUserEmail: '',
        operationUserId: '',
        operationUserName: '',
        remark: '',
        businessLicenseUri: '',
        domain: '',
        packages: '',
        charges: ''
      },
      loading: false,
      erpStatus: '',
      currentRow: {},
      baseDomain: '.jomalls.com',
      cloneEditForm: {}
    }
  },
  mounted() {
    this.cloneEditForm = JSON.parse(JSON.stringify(this.editForm))
    this.getTableList()
    this.getStatusList()
    this.getUserList()
  },
  computed: {
    ...mapState(['userInfo']),
    tableColumns() {
      const statusMap = this.serviceStatusLists.reduce((map, item) => {
        map[item.remark] = { color: item.color }
        return map
      }, {})

      return [
        {
          label: '公司名称',
          key: 'companyName',
          width: 130,
          align: 'center'
        },
        {
          label: '所属行业',
          key: 'industry',
          width: 130,
          align: 'center'
        },
        {
          label: '注册地址',
          key: 'registeredAddress',
          width: 130,
          align: 'center'
        },
        {
          label: '办公地址',
          key: 'officeAddress',
          width: 130,
          align: 'center'
        },
        {
          label: '业务对接人',
          key: 'contactUserName',
          width: 130,
          align: 'center'
        },
        {
          label: '对接人职位',
          key: 'contactUserTitle',
          width: 130,
          align: 'center'
        },
        {
          label: '对接人电话',
          key: 'contactUserPhone',
          width: 130,
          align: 'center'
        },
        {
          label: '对接人邮箱',
          key: 'contactUserEmail',
          width: 160,
          align: 'center'
        },
        {
          label: '营业执照',
          key: 'businessLicenseUri',
          width: 100,
          align: 'center',
          render: (row) => {
            if (!row.businessLicenseUri) return <span>-</span>
            return (
              <el-image
                src={row.businessLicenseUri}
                style="width:30px;height:30px"
                fit="cover"
                preview-src-list={[row.businessLicenseUri]}
                preview-teleported
              />
            )
          }
        },
        {
          label: 'ERP服务',
          key: 'erpServiceStatusName',
          width: 100,
          align: 'center',
          render: (item) => {
            const status = statusMap[item.erpServiceStatusName]
            if (!status) return <span>未知</span>
            return (
              <el-tag
                size="small"
                style={{
                  color: status.color,
                  fontWeight: 600,
                  backgroundColor: status.color + '20',
                  borderColor: status.color + '50'
                }}>
                {item.erpServiceStatusName}
              </el-tag>
            )
          }
        },
        {
          label: '域名',
          key: 'domain',
          width: 180,
          align: 'center',
          render: (row) => {
            if (!row.domain) return <span>-</span>
            // const fullDomain = row.domain + '.jomalls.com'
            const linkUrl = `https://${row.domain}`
            return (
              <a href={linkUrl} target="_blank" style="color: #409EFF">
                {row.domain}
              </a>
            )
          }
        },
        {
          label: '客户编码',
          key: 'erpUserMark',
          width: 100,
          align: 'center'
        },
        {
          label: '套餐',
          key: 'packages',
          width: 130,
          align: 'center'
        },
        {
          label: '资费',
          key: 'charges',
          width: 130,
          align: 'center'
        },
        {
          label: '备注',
          key: 'remark',
          width: 130,
          align: 'center'
        },
        {
          label: '客户运营',
          key: 'operationUserName',
          width: 130,
          align: 'center'
        },
        {
          label: '创建时间',
          key: 'createTime',
          width: 130
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 120,
          render: (item) => {
            const status = item.erpServiceStatusName
            const isOpen = status === '已开通'
            const isActivating = status === '开通中'
            const canOpen = ['未开通', '开通失败'].includes(status)
            const canDelete = ['未开通', '已关闭', '开通失败'].includes(status)
            const imgStyle = {
              width: '24px',
              height: '24px',
              cursor: 'pointer',
              verticalAlign: 'middle'
            }
            return (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '6px'
                }}>
                <img
                  src={require('@/assets/images/edit.png')}
                  style={{
                    ...imgStyle,
                    opacity: isActivating ? 0.4 : 1,
                    cursor: isActivating ? 'not-allowed' : 'pointer'
                  }}
                  title="编辑"
                  onClick={() => {
                    if (!isActivating) this.handleOperation('edit', item)
                  }}
                />
                <img
                  src={require('@/assets/images/log.png')}
                  style={imgStyle}
                  title="操作日志"
                  onClick={() => this.handleOperation('log', item)}
                />
                <el-dropdown
                  trigger="click"
                  onCommand={(cmd) => this.handleOperation(cmd, item)}>
                  <span style={{ lineHeight: 1, display: 'inline-block' }}>
                    <img
                      title={isActivating ? '开通中，更多操作不可点击' : '更多'}
                      src={require('@/assets/images/more.png')}
                      style={{
                        ...imgStyle,
                        opacity: isActivating ? 0.4 : 1,
                        cursor: isActivating ? 'not-allowed' : 'pointer'
                      }}
                    />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    {canOpen && (
                      <el-dropdown-item command="openErp">
                        <el-button
                          type="text"
                          style={{ color: '#2776ce', fontWeight: 'bold' }}>
                          开通ERP
                        </el-button>
                      </el-dropdown-item>
                    )}
                    {isOpen && (
                      <el-dropdown-item command="closeErp">
                        <el-button
                          type="text"
                          style={{ color: '#909399', fontWeight: 'bold' }}>
                          关闭ERP
                        </el-button>
                      </el-dropdown-item>
                    )}
                    {isOpen && (
                      <el-dropdown-item command="giftOrder">
                        <el-button
                          type="text"
                          style={{ color: '#9B59B6', fontWeight: 'bold' }}>
                          赠送订单
                        </el-button>
                      </el-dropdown-item>
                    )}
                    {canDelete && (
                      <el-dropdown-item command="delete">
                        <el-button
                          type="text"
                          style={{ color: '#F56C6C', fontWeight: 'bold' }}>
                          删除
                        </el-button>
                      </el-dropdown-item>
                    )}
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            )
          }
        }
      ]
    }
  },
  methods: {
    getUserList() {
      get('platform/user/list')
        .then((res) => {
          if (res.code !== 200) return
          this.userLists = res.data || []
        })
        .catch((error) => {
          console.error('获取用户列表失败:', error)
        })
    },
    getStatusList() {
      get('customer/info/serviceStatusList')
        .then((res) => {
          if (res.code !== 200) return
          this.serviceStatusLists = res.data || []
        })
        .catch((error) => {
          console.error('获取状态列表失败:', error)
        })
    },
    handleOperation(command, row) {
      this.commandTitle = command
      this.erpStatus = row.erpServiceStatusName
      switch (command) {
        case 'openErp':
          this.openCustomerInfo(row)
          break
        case 'edit':
          this.updateCustomerInfo(row)
          break
        case 'closeErp':
          this.closeCustomerInfo(row)
          break
        case 'giftOrder':
          this.giftOrderInfo(row)
          break
        case 'delete':
          this.deleteSection(row)
          break
        case 'log':
          this.logInfo(row)
          break
      }
    },
    sizeChange(pageSize) {
      this.centerPageOptions.pageSize = pageSize
      this.getTableList()
    },
    onCurrentChange(currentPage) {
      this.centerPageOptions.currentPage = currentPage
      this.getTableList()
    },
    async getTableList() {
      this.loading = true
      const { pageSize, currentPage } = this.centerPageOptions
      post('customer/info/pageList', {
        pageSize,
        currentPage,
        ...this.searchForm
      })
        .then((res) => {
          if (res.code !== 200) return
          this.sourceData = res.data.records
          this.centerPageOptions.total = res.data.total
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSelectionChange(selection) {
      this.selections = selection
    },
    addCustomerInfo() {
      this.commandTitle = 'add'
      this.editForm.operationUserId = this.userInfo?.id || ''
      this.editForm = JSON.parse(JSON.stringify(this.cloneEditForm))
      this.editDialog = true
      this.$nextTick(() => {
        this.$refs.customerRef && this.$refs.customerRef.clearForm()
      })
    },
    updateCustomerInfo(v) {
      this.getListInfo(v.id)
        .then((res) => {
          if (res.code === 200) {
            const parts = /^(.*)(\.(([^.]+)\.([^.]+)))$/.exec(
              res.data?.customerInfo.domain
            )
            if (parts) {
              const name = parts[1]
              const tld = '.' + parts[3]
              res.data.customerInfo.domain = name
              this.baseDomain = tld
            }
            this.editForm = res.data?.customerInfo
            this.editDialog = true
            this.$nextTick(() => {
              this.$refs.customerRef && this.$refs.customerRef.clearForm()
            })
          }
        })
        .catch((err) => {
          console.error(err)
          this.$message.error('加载详情失败')
        })
    },
    async onSubmit(editForm) {
      try {
        // 匹配操作人员姓名
        const targetUser = this.userLists.find(
          (item) => item.id === editForm.operationUserId
        )
        editForm.operationUserName = targetUser?.realName || ''
        // 拼接完整域名
        const fullDomain = editForm.domain + this.baseDomain
        let url = ''
        const params = { ...editForm }
        const commandMap = {
          add: () => {
            url = 'customer/info/add'
          },
          edit: () => {
            url = 'customer/info/update'
            params.domain = fullDomain
          },
          openErp: () => {
            url =
              this.erpStatus === '未开通'
                ? 'customer/info/openService'
                : 'customer/info/reOpenService'
            params.serviceType = 1
            params.customerId = editForm.id
            params.domain = fullDomain
          }
        }
        const handler = commandMap[this.commandTitle]
        if (!handler) {
          this.$message.warning('未知操作类型')
          return
        }
        handler()
        const res = await post(url, params)
        if (res.code === 200) {
          this.$message.success('操作成功！')
          this.editDialog = false
          this.getTableList()
        }
      } catch (err) {
        // 捕获网络、接口异常
        console.error('提交接口异常：', err)
        this.$message.error('网络异常，请稍后重试')
      }
    },
    async getListInfo(id) {
      return await get(`customer/info/get/${id}`)
    },
    openCustomerInfo(v) {
      const DEFAULT_FORM = {
        domain: '',
        packages: 'PAYBASE',
        charges: '0.2元/单'
      }
      this.getListInfo(v.id)
        .then((res) => {
          const parts = /^(.*)(\.(([^.]+)\.([^.]+)))$/.exec(
            res.data?.customerInfo.domain
          )
          if (parts) {
            const name = parts[1]
            const tld = '.' + parts[3]
            res.data.customerInfo.domain = name
            this.baseDomain = tld
          }
          const customerData = res.data?.customerInfo
          this.editForm = {
            ...DEFAULT_FORM,
            ...customerData
          }
          this.editDialog = true
          this.$refs.customerRef && this.$refs.customerRef.clearForm()
        })
        .catch((err) => {
          console.error(err)
          this.$message.error('加载详情失败')
        })
    },
    async closeCustomerInfo(v) {
      try {
        await this.$confirm('确定对当前客户进行关闭ERP操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }
      try {
        const res = await post('customer/info/closeService', {
          customerId: v.id,
          serviceType: 1
        })
        if (res.code !== 200) return
        this.$message.success('关闭ERP成功！')
        this.getTableList()
      } catch (e) {
        console.error(e)
      }
    },
    giftOrderInfo(v) {
      this.currentRow = v
      this.giftOrderVisible = true
      this.giftOrderForm = {
        quantity: '',
        remark: ''
      }
      this.$nextTick(() => {
        this.$refs.giftOrderForm?.clearValidate()
      })
    },
    async submitGiftOrder() {
      if (this.submitLoading) return
      this.$refs.giftOrderForm.validate(async (valid) => {
        if (!valid) return
        // 开启加载锁
        this.submitLoading = true
        try {
          const res = await addGiftOrders({
            apiName: this.currentRow.erpApiName,
            giftOrderQuantity: Number(this.giftOrderForm.quantity),
            remark: this.giftOrderForm.remark
          })
          if (res.code === 200) {
            this.$message.success(res.message)
            this.getTableList()
            this.giftOrderVisible = false
          }
        } catch (err) {
          this.$message.error('提交失败，请重试')
        } finally {
          // 无论成功失败，释放锁
          this.submitLoading = false
        }
      })
    },
    async deleteSection(v) {
      try {
        await this.$confirm('确定删除选中的信息？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }
      try {
        const res = await remove(`customer/info/delete/${v.id}`)
        if (res.code !== 200) return
        this.$message.success('删除成功！')
        this.getTableList()
      } catch (e) {
        console.error(e)
      }
    },
    async logInfo(v) {
      try {
        const res = await get(`customer/info/operationLog/${v.id}`)
        if (res.code !== 200) return
        this.logList = res.data || []
        this.logVisible = true
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.wraper {
  height: 100%;
  display: flex;
  overflow: hidden;
}
.page_right {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 5px;
  overflow: hidden;
  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    font-weight: bold;
  }
  .search_form {
    margin-top: 5px;
    margin-left: 10px;
  }

  .search_form > .el-form-item {
    margin-bottom: 5px;
  }
  .table-wrap {
    background: #fff;
    flex: 1;
    overflow: hidden;
    width: 100%;
    padding: 10px;
  }
}
</style>
