<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>

    <!-- 操作日志 -->
    <el-dialog
      title="操作日志"
      :close-on-click-modal="false"
      :visible.sync="noteVisible"
      width="500px">
      <ul style="color: #333; font-size: 12px; height: 400px; overflow: auto">
        <li v-for="(item, index) in logList" :key="index" style="height: 30px">
          ({{ index + 1 }})、{{ item.userName + '：' + item.msg }}
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
import axios from '../../common/api/axios'
import CustomForm from '@/common/components/base/CustomForm.vue'
import tableVue from '@/common/components/base/tableView.vue'
export default {
  name: 'system_users',
  components: {
    tableVue,
    CustomForm
  },
  data() {
    return {
      is_title: 1,
      noteVisible: false,
      sourceData: [],
      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: 'change'
            }
          ]
        },
        {
          prop: 'fixedFee',
          type: 'inputNumber',
          name: '固定费用',
          step: 0.01,
          min: 0,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入固定费用',
              trigger: 'change'
            }
          ],
          isShow: (formData) => formData.type === 1
        },
        {
          prop: 'unitType',
          type: 'radio',
          name: '计算单位',
          radioOptions: [
            {
              value: 'order',
              label: '按单'
            },
            {
              value: 'product',
              label: '按数量'
            }
          ],
          renderRules: (item) => [
            {
              required: true,
              message: '请选择计算单位',
              trigger: 'change'
            }
          ],
          isShow: (formData) => formData.type === 1
        },
        {
          prop: 'startFee',
          type: 'inputNumber',
          name: '起收费用',
          step: 0.01,
          min: 0,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入起收费用',
              trigger: 'change'
            }
          ],
          isShow: (formData) => formData.type === 2
        },
        {
          prop: 'incrementalFee',
          type: 'inputNumber',
          name: '每件加收',
          step: 0.01,
          min: 0,
          renderRules: (item) => [
            {
              required: true,
              message: '请输入每件加收',
              trigger: 'change'
            }
          ],
          isShow: (formData) => formData.type === 2
        },
        {
          prop: 'endFee',
          type: 'inputNumber',
          name: '上限费用 ',
          step: 0.01,
          min: 0,
          renderRules: (formData) => [
            {
              required: true,
              message: '请输入上限费用',
              trigger: 'change'
            },
            {
              validator: (rule, value, callback) => {
                if (Number(value) <= Number(formData.startFee)) {
                  callback(new Error('上限费用必须大于起收费用'))
                } else {
                  callback()
                }
              }
            }
          ],
          isShow: (formData) => formData.type === 2
        }
      ],
      dialogVisible: false,

      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      loading: false
    }
  },
  created() {
    this.getList()
  },
  computed: {
    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: 'unitType',
          width: '100',
          render: (item) => (
            <span key={item.id}>
              {item.unitType === 'order' ? (
                <el-tag type="danger">按单</el-tag>
              ) : item.unitType === 'product' ? (
                <el-tag type="primary">按数量</el-tag>
              ) : null}
            </span>
          )
        },
        {
          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:#409EFF"
                  class="el-icon-document"
                  onClick={(e) => this.showLog(item, 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>
          )
        }
      ]
    }
  },
  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
      }
    },

    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 = '/operationFeeManagement/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: 0,
            startFee: 0,
            incrementalFee: 0,
            endFee: 0,
            unitType: 'order'
          }
          for (const key in params) {
            params[key] = this.formData[key]
          }
          resolve(params)
        })
      ])

      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) {
          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 showLog(data, e) {
      try {
        const url = '/operationFeeManagement/listLog'
        const res = await axios.get(url, { params: { id: data.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)
      }
    },
    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;
}
</style>
