<template>
  <div class="recharge-record card">
    <div class="search">
      <CustomForm
        :formConfig="queryformConfig"
        v-model="queryFormData"
        :is-custom-button="false"
        :isFlex="false">
        <template slot="btn">
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
        </template>
      </CustomForm>
    </div>
    <div class="table_wrap" v-loading="loading">
      <table-vue
        :sourceData="sourceData"
        ref="multipleTable"
        :tableColumns="usersTableColumns"
        @currentChange="currentTabFn"
        @selectionChange="selectionChange"></table-vue>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="paginationOptions.total"
        :page-size="paginationOptions.pageSize"
        :current-page="paginationOptions.currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"></el-pagination>
    </div>
  </div>
</template>
<script>
import axios from '../../common/api/axios'
import CustomForm from '@/common/components/base/CustomForm.vue'
import { mapState } from 'vuex'
import tableVue from '@/common/components/base/tableView.vue'

export default {
  name: 'erpManagementList',
  components: {
    tableVue,
    CustomForm
  },
  data() {
    return {
      is_title: 1,
      ishowForm: false,
      select: '',
      sourceData: [],
      serviceNameList: new Map(),
      formData: {},
      queryFormData: {},
      queryformConfig: [
        {
          prop: 'name',
          type: 'select',
          name: '名称',
          options: []
        }
      ],

      dialogVisible: false,
      formId: null,

      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      details: [],
      loading: false
    }
  },
  async created() {
    await this.getServiceNameList()

    this.getList()
  },
  computed: {
    ...mapState(['reqMenu', 'employee']),
    usersTableColumns() {
      return [
        {
          label: 'namespace',
          key: 'namespace'
        },
        {
          label: '服务名称',
          key: 'name',

          render: (item) => (
            <span>{this.serviceNameList.get(item.name).label}</span>
          )
        },
        {
          label: '服务类型',
          key: 'type',

          render: (item) => (
            <span>{item.type === 'basics' ? '基础' : '增值'}</span>
          )
        },

        {
          label: '收费标准',
          key: 'rates'
        },

        {
          label: '状态',
          key: 'enable',
          width: '100',

          render: (item) => <span>{item.enable ? '启用' : '停用'}</span>
        },

        {
          label: '是否参与折扣',
          key: 'discount',
          width: '100',

          render: (item) => <span>{item.discount === true ? '是' : '否'}</span>
        }
      ]
    },

    funcRoleList() {
      if (this.roleList.length > 0) {
        return this.roleList.filter((item) => item.type === 'FUNCTION_ROLE')
      }
      return []
    },
    dataRoleList() {
      if (this.roleList.length > 0) {
        return this.roleList.filter((item) => item.type === 'DATA_ROLE')
      }
      return []
    }
  },
  watch: {
    formData: {
      handler(newValue) {
        // console.log(368, newValue)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    sizeChange(value) {
      this.paginationOptions.pageSize = value
      this.getList()
    },
    onCurrentChange(value) {
      this.paginationOptions.currentPage = value
      this.getList()
    },
    selectionChange(selection) {
      if (selection.length > 0) {
        this.select = selection
      }
    },

    setempNo(id) {
      for (const iterator of this.employee) {
        if (iterator.id === id) {
          this.addcurrencyform.empNumber = iterator.empNumber
          break
        }
      }
    },
    search() {
      this.getList()
    },
    currentTabFn(val) {
      if (val.row) {
        this.formId = val.row.id
      }
    },
    // 修改新增
    async addDialog(id, e) {
      e && e.stopPropagation()
      this.ishowForm = true
      try {
        if (id) {
          this.is_title = 2
          const url = '/serviceManagement/get'
          const res = await axios.get(url, { params: { id } })

          this.formData = { ...res.data }
          this.formData.nameObj = this.serviceNameList.get(this.formData.name)
          this.formData.serveType =
            this.serviceNameList.get(this.formData.name).type === 'basics'
              ? '基础'
              : '增值'
          console.log(289, this.formData)
        } else {
          this.is_title = 1
        }
        this.dialogVisible = true
      } catch (error) {}
    },
    async checkData() {
      const [isValid, postData] = await Promise.all([
        new Promise((resolve) => {
          this.$refs.formRefs
            .validateForm()
            .then((res) => resolve(true))
            .catch((err) => {
              resolve(false)
              console.log(err)
            })
        }),
        new Promise((resolve) => {
          const params = {
            name: '',
            id: '',
            type: '',
            tollCollectionManner: '',
            rates: '',
            enable: '',
            discount: '',
            remarks: ''
          }
          for (const key in params) {
            params[key] = this.formData[key]
          }
          resolve(params)
        })
      ])
      console.log(isValid, postData)

      return { isValid, postData }
    },

    // 新增
    async addServiceManagement() {
      const isAdd = this.is_title === 1
      const url = isAdd ? '/serviceManagement/add' : '/serviceManagement/update'
      try {
        const { isValid, postData } = await this.checkData()
        if (isValid) {
          console.log('add', this.formData)
          const finalData = isAdd ? { ...postData, id: undefined } : postData
          const res = await axios.post(url, finalData)
          if (res.code !== 200) {
            return
          }

          this.dialogVisible = false
          this.getList()
          this.$message.success(isAdd ? '新增成功' : '更新成功')
        } else {
          console.log()
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 查询
    getList() {
      this.loading = true
      const { pageSize, currentPage } = this.paginationOptions
      axios
        .post('serviceManagementLog/list_page', {
          pageSize,
          currentPage,
          ...this.queryFormData
        })
        .then((res) => {
          if (res.code === 200) {
            this.sourceData = res.data.records
            this.paginationOptions.total = res.data.total
          } else {
            this.$alert(res.message, '错误提示', {
              dangerouslyUseHTMLString: true
            })
          }
          this.loading = false
        })
    },

    // 删除
    deleteSection(data, e) {
      e && e.stopPropagation()
      const ids = [data.id].join()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          axios
            .get('serviceManagement/delete', {
              params: {
                ids
              }
            })
            .then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getList()
              }
            })
        })
        .catch(() => {})
    },
    async closedFn() {
      this.dialogVisible = false

      this.formData = { enable: true, discount: true }
      await this.$refs.formRefs?.resetFields()
    },
    async getServiceNameList() {
      try {
        const { data } = await axios.get('serviceManagement/serviceNameList')
        const newData = data.map((el) => {
          return {
            label: el.remark,
            value: el.code,
            type: el.type
          }
        })
        this.serviceNameList = new Map(
          newData.map((item) => [
            item.value,
            { label: item.label, type: item.type, value: item.value }
          ])
        )
        this.queryformConfig[0].options = [...newData]
        console.log(509, this.serviceNameList)
      } catch (error) {
        console.log(error)
      }
    },
    async enableChange(item, value) {
      this.loading = true
      try {
        const params = {
          id: item.id,
          status: value
        }
        console.log(item, value)

        await axios.get('/serviceManagement/updateStatus', { params })
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    async updateListFn() {
      this.loading = true
      try {
        await axios.get('serviceManagement/syncErp')
      } catch (error) {
        console.log(error)
        this.$message.warning(error.message)
      } finally {
        this.loading = false
      }
    },
    toList() {}
  }
}
</script>
<style scoped lang="less">
.recharge-record {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  &::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;
    }
  }
}
.wraper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table_wrap {
  flex: 1;
  padding: 0;
}

.circle {
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  margin-right: 5px;
}

.my-table .first {
  background-color: red !important;
  color: #fff !important;
}
::v-deep.switchStyle .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
  span {
    font-size: 12px !important;
  }
}
.el-switch__core {
  background-color: rgba(166, 166, 166, 1);
}
::v-deep.switchStyle .el-switch__label--left {
  z-index: 9;
  left: 20px;
}
::v-deep.switchStyle .el-switch__label--right {
  z-index: 9;
  right: 20px;
}
::v-deep.switchStyle .el-switch__label.is-active {
  display: block;
}
::v-deep.switchStyle.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 50px !important;
}
</style>
