<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: 'input',
          name: '名称',
          options: []
        },
        {
          prop: 'type',
          name: '费用类型',
          type: 'select',
          labelWidth: '20',
          options: [
            { label: '固定', value: 1 },
            { label: '浮动', value: 2 }
          ]
        }
      ],
      editformConfig: [
        {
          prop: 'name',
          type: 'input',
          name: '名称',
          options: [],
          renderRules: (item) => [
            {
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            }
          ]
        },
        {
          prop: 'type',
          name: '费用类型',
          type: 'select',
          options: [
            { label: '固定', value: 1 },
            { label: '浮动', value: 2 }
          ],
          max: 1,
          renderRules: (item) => [
            {
              required: true,
              message: '请选择服务类型',
              trigger: 'blur'
            }
          ]
        },
        {
          prop: 'fixedFee',
          type: 'inputNumber',
          name: '固定费用',
          step: 0.01,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入固定费用',
              trigger: 'blur'
            }
          ],
          isShow: (formData) => formData.type === 1
        },
        {
          prop: 'startFee',
          type: 'inputNumber',
          name: '起收费用',
          step: 0.01,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入起收费用',
              trigger: 'blur'
            }
          ],
          isShow: (formData) => formData.type === 2
        },
        {
          prop: 'incrementalFee',
          type: 'inputNumber',
          name: '每件加收',
          step: 0.01,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入每件加收',
              trigger: 'blur'
            }
          ],
          isShow: (formData) => formData.type === 2
        },
        {
          prop: 'endFee',
          type: 'inputNumber',
          name: '上限费用 ',
          step: 0.01,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入上限费用',
              trigger: 'blur'
            }
          ],
          isShow: (formData) => formData.type === 2
        }
      ],
      dialogVisible: false,
      formId: null,

      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      details: [],
      loading: false
    }
  },
  created() {
    this.getList()
  },
  computed: {
    ...mapState(['reqMenu', 'employee']),
    usersTableColumns() {
      return [
        {
          label: '名称',
          key: 'name',
          width: ''
        },
        {
          label: ' 费用类型 ',
          key: 'type',
          width: '',
          render: (item) => (
            <span>
              {item.type === 1 ? (
                <el-tag type="success">固定类型</el-tag>
              ) : (
                <el-tag type="warning">浮动类型</el-tag>
              )}
            </span>
          )
        },
        {
          label: '固定费用',
          key: 'fixedFee',
          width: '150'
        },
        {
          label: '起收费用',
          key: 'startFee',
          width: '150'
        },
        {
          label: '每件加收',
          key: 'incrementalFee',
          width: '150'
        },
        {
          label: '上限费用',
          key: 'endFee',
          width: '150'
        },
        {
          label: '创建时间',
          key: 'createTime',
          width: ''
        },
        {
          label: '更新时间',
          key: 'updateTime',
          width: ''
        },
        {
          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: '',
            fixedFee: '',
            startFee: '',
            incrementalFee: '',
            endFee: ''
          }
          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
        ? '/operationFeeManagement/add'
        : '/operationFeeManagement/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('operationFeeManagement/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('operationFeeManagement/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()
    }
  }
}
</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;
}
/* 选中按钮的背景色和边框色 */
::v-deep .el-radio-button.is-checked .el-radio-button__inner {
  background-color: #1565c0 !important;
  border-color: #1565c0 !important;
  color: #fff !important;
}
::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #1565c0 !important;
  border-color: #1565c0 !important;
  color: #fff !important;
}

/* 鼠标悬浮时的颜色 */
::v-deep .el-radio-button__inner:hover {
  border-color: #1565c0 !important;
  color: #1565c0 !important;
}
</style>
