<template>
  <div>
    <!-- 违章处罚单弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules">
        <el-row style="display: flex; flex-direction: row">
          <el-form-item label="处罚单号" prop="violationCode">
            <el-input v-model="dialogForm.violationCode" placeholder="请输入处罚单号" disabled />
          </el-form-item>
          <el-form-item label="受罚工程" prop="proName">
            <el-input v-model="dialogForm.proName" placeholder="请选择受罚工程" disabled />
          </el-form-item>
          <el-form-item label="受罚承包商" prop="consName">
            <el-input v-model="dialogForm.consName" placeholder="请选择受罚承包商" disabled />
          </el-form-item>
        </el-row>

        <el-row style="display: flex; flex-direction: row">
          <el-form-item label="责任人" prop="directorName">
            <el-input v-model="dialogForm.directorName" placeholder="请选择责任人" disabled />
          </el-form-item>
          <el-form-item label="承包商负责人" prop="personName">
            <el-input v-model="dialogForm.personName" placeholder="请选择承包商负责人" disabled />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="处罚原因" prop="punishmentReason">
              <el-input
                type="textarea"
                v-model="dialogForm.punishmentReason"
                placeholder="请输入处罚原因"
                clearable v-no-whitespace
                :autosize="{ minRows: 4, maxRows: 6 }"
                maxlength="1000"
                show-word-limit
                style="width: 515px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" :offset="0">
            <el-form-item label="处罚依据" prop="punishmentBasis">
              <el-input
                type="textarea"
                v-model="dialogForm.punishmentBasis"
                placeholder="请输入处罚依据"
                clearable v-no-whitespace
                :autosize="{ minRows: 4, maxRows: 6 }"
                maxlength="1000"
                show-word-limit
                style="width: 515px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="display: flex; flex-direction: row">
          <el-form-item label="处罚金额" prop="money">
            <div style="display: flex">
              <el-input
                v-model="dialogForm.money"
                placeholder="请输入处罚金额"
                clearable v-no-whitespace
                style="width: 200px"
                @input="violationAmountUpper"
              />
              <div style="width: 100px; margin-left: 10px">元（人民币）</div>
            </div>
          </el-form-item>
          <!-- 处罚金额大写 -->
          <el-form-item label="大写" prop="moneyUpper">
            <el-input v-model="dialogForm.moneyUpper" placeholder="处罚金额大写" disabled style="width: 400px" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24" :offset="0" style="display: flex; flex-direction: row">
            <el-form-item label="监督部门" prop="deptId">
              <treeselect
                style="width: 80%"
                ref="treeselect"
                v-model="dialogForm.deptId"
                :options="supervisionDepartmentOpts"
                :show-count="true"
                :noResultsText="'未找到相关部门！'"
                placeholder="请选择监督部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex; flex-direction: row">
          <el-form-item label="签发人" prop="signerName">
            <el-input v-model="dialogForm.signerName" placeholder="请输入签发人" disabled />
          </el-form-item>
          <el-form-item label="监督人" prop="supervisorId">
            <el-select v-model="dialogForm.supervisorId" placeholder="请选择监督人" @change="changeSupervisor" :disabled="dialogForm.deptId ? false : true">
              <el-option v-for="item in supervisorOpts" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="发现人" prop="createUserName">
            <el-input v-model="dialogForm.createUserName" placeholder="请输入发现人" disabled />
          </el-form-item>
        </el-row>
        <el-row style="display: flex; flex-direction: row">
          <el-form-item label="接收人" prop="personName">
            <el-input v-model="dialogForm.personName" placeholder="请输入接收人" disabled />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="dialogForm.remark"
                placeholder="请输入备注"
                clearable v-no-whitespace
                :autosize="{ minRows: 4, maxRows: 6 }"
                maxlength="1000"
                show-word-limit
                style="width: 515px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="dialogConfirm(1)" v-preventReClick="5000">确 定</el-button>
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="preview" v-loading.fullscreen.lock="isLoading">预 览</el-button>
        <el-button type="primary" size="small" @click="dialogConfirm(2)" v-preventReClick="5000">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog title="文件查看" :visible.sync="previewOpen" width="90%" append-to-body>
      <div style="width: 100%; height: 720px">
        <bns-kkFile-preview :items="filePreview"></bns-kkFile-preview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { numberToChinese } from '@/utils/bonus'
import { addIssueFine, getDeptPersonById, getViolationDetail, PreviewViolation } from '@/api/violation/violation'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/system/user'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'

export default {
  components: { bnsKkFilePreview, Treeselect },
  data() {
    return {
      row: {},
      dialogTitle: '违章处罚单',
      dialogVisible: false,
      isDialogDetail: false,
      dialogForm: {
        violationCode: undefined, // 处罚单号
        proName: undefined, // 受罚工程
        consName: undefined, // 受罚承包商
        directorName: undefined, // 责任人
        personName: undefined, // 承包商负责人
        punishmentReason: undefined, // 处罚原因
        punishmentBasis: undefined, // 处罚依据
        money: undefined, // 处罚金额
        moneyUpper: undefined, // 处罚金额大写
        deptId: undefined, // 监督部门
        deptName: undefined,
        signerName: undefined, // 签发人
        supervisorId: undefined, // 监督人
        supervisorName: undefined, // 监督人
        createUserName: undefined, // 发现人
        receiver: undefined, // 接收人
        remark: undefined, // 备注
      },
      // 监督部门-下拉框
      supervisionDepartmentOpts: [],
      // 监督人-下拉框
      supervisorOpts: [],
      dialogRules: {
        punishmentReason: [{ required: true, message: '请输入处罚原因', trigger: 'blur' }],
        punishmentBasis: [{ required: true, message: '请输入处罚依据', trigger: 'blur' }],
        money: [
          { required: true, message: '请输入处罚金额', trigger: 'blur' },
          {
            // 最多10位整数，最多2位小数
            pattern: /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/,
            message: '请输入正确的金额',
            trigger: 'blur',
          },
        ],
        deptId: [{ required: true, message: '请选择监督部门', trigger: 'change' }],
        supervisorId: [{ required: true, message: '请选择监督人', trigger: 'blur' }],
      },
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
      },
      previewOpen: false,
      isLoading: false, // 全屏loading
      selectSuper: {},
    }
  },
  created() {
    this.getDeptTree()
  },
  watch: {
    'dialogForm.deptId': function (newVal, oldVal) {
      console.log('deptId changed from', oldVal, 'to', newVal)
      if (oldVal !== undefined ) {
        this.dialogForm.supervisorId = this.$set(this.dialogForm, 'supervisorId', undefined)
        this.dialogForm.supervisorName = this.$set(this.dialogForm, 'supervisorName', undefined)
      }
      this.changeDept(newVal)
    },
  },
  methods: {
    // 打开违章弹框
    openDialog(row) {
      console.log('🚀 ~ openDialog ~ row:', row)
      this.row = row
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        getViolationDetail({ violationId: row.violationId }).then(res => {
          const { supervisorId, supervisorName } = res.data
          this.selectSuper = { value: supervisorId, label: supervisorName }
          this.dialogForm = res.data
          console.log('🚀 ~ openDialog ~ this.dialogForm', res.data)
          this.dialogForm.signerName = this.$store.state.user.userData.nickName
          this.dialogForm.signerId = this.$store.state.user.userData.userId
        })

      }, 100)

    },
    // 处理大写
    violationAmountUpper(value) {
      // 将金额转换为大写
      this.dialogForm.moneyUpper = numberToChinese(value)
    },
    // 违章弹框确定
    dialogConfirm(type) {
      this.$refs.dialogForm.validate(async valid => {
        let code = type === 1 ? '下发' : '保存'
        this.dialogForm.type = type.toString()
        if (type === 2) {
          addIssueFine(this.dialogForm).then(res => {
            this.$message.success(`处罚${code}成功`)
            this.dialogVisible = false
            this.$emit('getList')
          })
        } else {
          this.$refs.dialogForm.validate(valid => {
            if (!valid) {
              return false
            }
            addIssueFine(this.dialogForm).then(res => {
              this.$message.success(`处罚${code}成功`)
              this.dialogVisible = false
              this.$emit('getList')
            })
          })
        }
      })
    },
    getDeptTree() {
      deptTreeSelect({ type: '-1' }).then(response => {
        this.supervisionDepartmentOpts = response.data
      })
    },
    changeDept(val) {
      try {
        this.dialogForm.deptName = this.$refs.treeselect.getNode(val).label
        this.getDeptPerson(val)
      } catch (e) {}
    },
    getDeptPerson(val) {
      getDeptPersonById({ id: val }).then(response => {
        console.log('🚀 ~ getDeptPerson ~ response', response)
        this.supervisorOpts = response.data
      })
    },
    changeSupervisor(val) {
      console.log('🚀 ~ changeSupervisor ~ val', val)
      this.dialogForm.supervisorName = ''
      this.dialogForm.supervisorId = ''
      this.dialogForm.supervisorName = this.supervisorOpts.find(item => item.value == val).label
      this.dialogForm.supervisorId = val
      console.log('🚀 ~ changeSupervisor ~ this.dialogForm.supervisorName', this.dialogForm.supervisorName)
    },
    preview() {
      // console.log(this.$store.state.user)
      this.$confirm('预览会保存当前数据, 是否确认预览？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          try {
            this.dialogForm.type = '2'
            this.isLoading = true
            addIssueFine(this.dialogForm).then(res => {
              PreviewViolation({ violationId: this.row.violationId }).then(res => {
                this.isLoading = false
                if (res.code === 200) {
                  console.log('🚀 ~ file: PunishFormDialog.vue ~ line 97 ~ getViolationDetail ~ res', res)
                  this.filePreview = {
                    filePreviewUrl: 'punishSheet/' + res.msg,
                    fileName: '违章处罚单',
                  }
                  this.previewOpen = true
                }
              })
            })
          } catch (e) {
            this.isLoading = false
            console.log('🚀 ~ file: PunishFormDialog.vue ~ line 99 ~ getViolationDetail ~ e', e)
          }
        })
        .catch(() => {})
    },
  },
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
  .card-header {
    font-size: 16px;
    font-weight: 700;
  }
}
</style>
