<template>
  <div class="wraper">
    <CustomForm
      :formConfig="queryformConfig"
      v-model="queryFormData"
      @addDialog="addDialog"
      @searchFn="search"
      :isFlex="false"></CustomForm>
    <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>

    <!-- 弹出层 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="is_title == 1 ? '新增' : '编辑'"
      :visible.sync="dialogVisible"
      @closed="closedFn"
      width="590px">
      <CustomForm
        formItemWidth="50%"
        ref="formRefs"
        v-model="formData"
        :formConfig="editformConfig"
        :isCustomButton="false"
        formLabelWidth="100px"></CustomForm>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="mini"
          style="width: 100px">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="addServiceManagement"
          size="mini"
          style="width: 100px">
          确认
        </el-button>
      </span>
    </el-dialog>
  </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: 'system_users',
  components: {
    tableVue,
    CustomForm
  },
  data() {
    return {
      is_title: 1,
      ishowForm: false,
      select: '',
      sourceData: [],
      serviceNameList: [],
      formData: {},
      queryFormData: {},
      queryformConfig: [
        {
          prop: 'name',
          type: 'select',
          name: '名称',
          options: []
        },
        {
          prop: 'enable',
          type: 'select',
          name: '状态',
          options: [
            { label: '启用', value: true },
            { label: '停用', value: false }
          ]
        }
      ],
      editformConfig: [
        {
          prop: 'name',
          type: 'select',
          name: '名称',
          options: [],
          renderRules: (item) => [
            {
              required: true,
              message: '请选择名称',
              trigger: 'change'
            }
          ]
        },
        {
          prop: 'type',
          type: 'select',
          name: '服务类型',
          options: [
            { label: '基础', value: 'basics' },
            { label: '增值', value: 'appreciation' }
          ],
          renderRules: (item) => [
            {
              required: true,
              message: '请选择服务类型',
              trigger: 'change'
            }
          ]
        },
        {
          prop: 'tollCollectionManner',
          type: 'select',
          name: '收费方式',
          options: [
            { label: '按单', value: 'order' },
            { label: '按月', value: 'monthly' },
            { label: '免费', value: '免费' }
          ],
          renderRules: (item) => [
            {
              required: true,
              message: '请选择收费方式',
              trigger: 'change'
            }
          ]
        },
        {
          prop: 'rates',
          type: 'input',
          name: '收费标准',
          renderRules: (item) => [
            {
              required: item.tollCollectionManner !== '免费',
              validator: (rule, value, callback) => {
                if (item.tollCollectionManner !== '免费') {
                  if (value === '' || value === null || value === undefined) {
                    return callback(new Error('请输入收费标准'))
                  }
                }

                const numValue = Number(value)
                if (isNaN(numValue)) {
                  return callback(new Error('请输入有效数字'))
                }

                if (numValue < 0) {
                  return callback(new Error('数值必须大于等于0'))
                }

                // 校验通过
                callback()
              },
              trigger: 'blur'
            }
          ]
        },
        {
          prop: 'enable',
          type: 'radio',
          name: '服务启用状态',
          defaultValue: true,
          radioOptions: [
            { label: '启用', value: true },
            { label: '停用', value: false }
          ]
        },
        {
          prop: 'discount',
          type: 'radio',
          name: '参与折扣',
          defaultValue: true,
          radioOptions: [
            { label: '是', value: true },
            { label: '否', value: false }
          ]
        },
        {
          prop: 'remarks',
          type: 'textarea',
          name: '备注'
        }
      ],
      dialogVisible: false,
      formId: null,

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

    this.getList()
  },
  computed: {
    ...mapState(['reqMenu', 'employee']),
    usersTableColumns() {
      return [
        {
          label: '服务名称',
          key: 'name',
          width: '',
          render: (item) => <span>{this.serviceNameList.get(item.name)}</span>
        },
        {
          label: '服务类型',
          key: 'type',
          width: '',

          render: (item) => (
            <span>{item.type === 'basics' ? '基础' : '增值'}</span>
          )
        },
        {
          label: '收费方式',
          key: 'tollCollectionManner',
          width: '',

          render: (item) => (
            <span>
              {item.tollCollectionManner === 'order'
                ? '按单'
                : item.tollCollectionManner === 'monthly'
                ? '按月'
                : '免费'}
            </span>
          )
        },
        {
          label: '收费标准',
          key: 'rates',
          width: ''
        },
        {
          label: '状态',
          key: 'enable',
          width: '100',

          render: (item) => (
            <span>{item.enable === true ? '启用' : '停用'}</span>
          )
        },
        {
          label: '创建时间',
          key: 'createTime',
          width: ''
        },
        {
          label: '更新时间',
          key: 'updateTime',
          width: ''
        },
        {
          label: '是否参与折扣',
          key: 'discount',
          width: '100',

          render: (item) => <span>{item.discount === true ? '是' : '否'}</span>
        },
        {
          label: '备注',
          key: 'remarks',
          width: '250'
        },
        {
          label: '相关操作',
          key: '',
          fixed: 'right',
          width: '130',
          render: (item) => (
            <div>
              <span title="编辑" class="icon-view ">
                <i
                  class="el-icon-edit-outline"
                  style="color:#E6A23C"
                  onClick={(e) => this.addDialog(item.id, e)}></i>
              </span>

              <span title="删除" class="icon-view ">
                <i
                  style="color:#F56C6C"
                  class="el-icon-delete"
                  onClick={(e) => this.deleteSection(item, e)}></i>
              </span>
            </div>
          )
        }
      ]
    },

    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 }
        } 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('serviceManagement/list_page', {
          pageSize,
          currentPage,
          ...this.queryFormData
        })
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.sourceData = res.data.records
            this.paginationOptions.total = res.data.total
          } else {
            this.$alert(res.message, '错误提示', {
              dangerouslyUseHTMLString: true
            })
          }
        })
    },

    // 删除
    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.value,
            value: el.key
          }
        })
        this.serviceNameList = new Map(
          newData.map((item) => [item.value, item.label])
        )
        console.log(509, this.serviceNameList)

        this.queryformConfig[0].options = [...newData]
        this.editformConfig[0].options = [...newData]
      } catch (error) {
        this.queryformConfig[0].options = []
        this.editformConfig[0].options = []
        console.log(error)
      }
    }
  }
}
</script>
<style scoped>
.wraper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table_wrap {
  flex: 1;
}

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

.my-table >>> .first {
  background-color: red !important;
  color: #fff !important;
}
</style>
