<!-- 添加/编辑 -->
<template>
  <el-dialog :title="title" :visible.sync="isShow" :close-on-click-modal="false" class="drawer-box" width="700px" @close="handleCancel" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top">
      <el-row>
        <el-col :span="12">
          <el-form-item label="费用类型" prop="feeType">
            <el-select v-model="form.feeType" class="wd100" size="small">
              <el-option v-for="item in feeTypeList" :key="item.id" :label="item.label" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="form.roleIds" multiple class="wd100" size="small">
              <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="限定金额" prop="amount">
            <el-input-number class="wd100" :controls="false" size="small" v-model="form.amount" placeholder="请输入"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-cascader clearable v-model="form.deptId" size="small" filterable class="wd100" :options="$store.getters.userDeptTree" :props="$store.getters.newDefaultProps"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="出差区域" prop="area">
            <el-cascader size="small" filterable multiple clearable :props="defaultProps" class="wd100" v-model="form.area" :options="$store.getters.areaTree"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" @click="handleCancel" size="small">取消</el-button>
      <el-button type="primary" :loading="btnLoading" size="small" @click="handleSave">{{!id?'添加':'编辑'}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createFeeManage, updateFeeManage, deleteFeeManage, getFeeManage, getFeeManagePage, exportFeeManageExcel } from "@/api/bs/feeManage";
import VerifyFunc from '@/utils/verity'
import { listData } from "@/api/system/dict/data";
import { listSimpleDepts } from "@/api/system/dept";
import {
  listUser,
} from "@/api/system/user";
export default {
  name: '',
  props: {
    id: [String, Number],
    isOpen: Boolean,
  },
  components: {
    CommonName: () => import('@/components/CommonName'),
    AreaTree: () => import('@/components/AreaTree')
  },
  watch: {
    isOpen: {
      handler(val) {
        this.isShow = val
        this.title = this.id ? '编辑费用' : '添加费用'
        if (val) {
          this.handleInitForm()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.handleInit()
  },

  data() {
    return {
      companyName: window.localStorage.getItem('cn'),
      isShow: false,
      userList: [],
      feeTypeList: [],
      defaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        checkStrictly: false,
        multiple: true,
        emitPath: false
      },
      btnLoading: false,
      rules: {
        amount: [{ required: true, message: "请输入", trigger: "blur" }, { validator: VerifyFunc.newNumber }],
        deptId: [{ required: true, message: "请选择", trigger: "change" }],
        area: [{ required: true, message: "请选择", trigger: "change" }],
        feeType: [{ required: true, message: "请选择", trigger: "change" }],
        roleIds: [{ required: true, message: "请选择", trigger: "change" }],
      },
      form: {
        feeType: null,
        deptId: null,
        area: [],
        amount: undefined,
        roleIds: [],
      },
      deptOptions: [],
    }
  },

  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listSimpleDepts().then(response => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
        this.deptOptions && this.deptOptions.length && this.getList(this.deptOptions[0].id)
      });
    },
    /** 查询用户列表 */
    getList(id) {
      return new Promise((resolve) => {
        let queryParams = {
          pageNo: 1,
          pageSize: 100,
          username: undefined,
          mobile: undefined,
          status: undefined,
          deptId: id,
          createTime: []
        }

        listUser(queryParams).then(response => {
          this.userList = response.data.list || [];
          this.$emit('onList', this.userList)
          resolve(this.userList)
        })
      })
    },
    handleInit() {
      listData({
        pageNo: 1,
        pageSize: 50,
        dictType: 'bs_fee_type',
      }).then((res) => {
        this.feeTypeList = res.data.list || []
        this.$emit('onFeeType', this.feeTypeList)
      })
      this.getTreeselect()

    },
    handlePayCancel() {
      this.payShow = false
    },
    handleBeginScan() {
      if (!(this.fileList && this.fileList.length)) {
        return this.$fm('请上传营业执照！')
      }
    },
    // id 不存在 新增 否则编辑
    handleInitForm(id = this.id) {
      // 初始化参数
      if (!id) {
        this.form = {
          feeType: null,
          deptId: null,
          area: [],
          amount: undefined,
          roleIds: [],
        }
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.resetFields()
          this.$refs.form && this.$refs.form.clearValidate()
        })
      } else {
        getFeeManage(id).then(res => {
          this.form = {
            ...(res.data || {}),
            feeType: Number(res.data.feeType)
          }
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        })
      }
    },
    handleClose() {
      this.$emit('onClose')
    },
    handleSave() {
      this.$nextTick(() => {
        this.$refs.form.validate((bool) => {
          if (bool) {
            // 编辑
            if (this.id) {
              this.btnLoading = true
              updateFeeManage(this.form).then((res) => {
                this.btnLoading = false
                this.$modal.msgSuccess(`编辑成功啦！`);
                this.$emit('onConfirm')
              }).catch(() => {
                this.btnLoading = false
              })
            } else {
              this.btnLoading = true
              createFeeManage(this.form).then((res) => {
                this.btnLoading = false
                this.$emit('onConfirm')
                this.$modal.msgSuccess(`新增成功啦！`);
              }).catch(() => {
                this.btnLoading = false
              })
            }

          } else {
            this.$nextTick(() => {
              this.$scErr()
            })
          }
        })
      })
    },
    handleCancel() {
      this.$emit('onCancel')
    },
    handleRemove(file, files) {
      this.fileList = []
      this.form.logoUrl = null
    },
    onUploadChange(file, files) {
      if (['image/png', 'image/jpeg'].includes(file.raw.type)) {
        if (file.size / 1024 > 5000) {
          setTimeout(() => {
            this.$fm('文件超过5Mb，请压缩后上传!')
          }, 10)
          files.splice(files.length - 1, 1)
          return
        }
        this.fileList = []
        this.fileList.push(file)
      } else {
        this.$fm('不支持此文件类型，请重试！')
      }
    },
  }
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/edit/index.scss';
</style>