<template>
  <div id="current_ent_info">
    <el-card v-loading="loading">
      <div slot="header">
        <span>企业信息</span>
        <el-button
            @click="showEditCompany"
            style="float: right; padding: 0 5px"
            type="text"
        >修改
        </el-button
        >
        <el-button
            @click="handleRefresh"
            style="float: right; padding: 0 5px"
            type="text"
        >刷新
        </el-button
        >
      </div>
      <div style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业名称：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entName"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >企业简称：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entShortName"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业税号：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entTaxId"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >银行名称：
          </el-col
          >
          <el-col :span="8">
            <span v-text="bankName"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业类型：
          </el-col
          >
          <el-col :span="8">
            <span v-text="fmtEntType"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >银行账号：
          </el-col
          >
          <el-col :span="8">
            <span v-text="bankAccountNumber"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业地址：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entAddress"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >收款人：
          </el-col
          >
          <el-col :span="8">
            <span v-text="payees"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业电话：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entPhone"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >审核者：
          </el-col
          >
          <el-col :span="8">
            <span v-text="reviewers"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >企业联系人：
          </el-col
          >
          <el-col :span="8">
            <span v-text="entContactPerson"></span>
          </el-col>
          <el-col :span="4" style="text-align: right"
          >开票人：
          </el-col
          >
          <el-col :span="8">
            <span v-text="drawers"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >默认开票设备：
          </el-col
          >
          <el-col :span="8">
            <span v-text="fmtDefaultInvoiceDevice"></span>
          </el-col>
          <el-col :span="4" style="text-align: right">可用税率：</el-col>
          <el-col :span="8">
            <span v-text="availableTaxes"></span>
          </el-col>
        </el-row>
        <br/>
        <el-row :gutter="20">
          <el-col :span="4" style="text-align: right"
          >开票默认商品税率（%）：
          </el-col
          >
          <el-col :span="8">
            <span v-text="defaultTaxRate"></span>
          </el-col>
          <el-col :span="4" style="text-align: right">所属税局：</el-col>
          <el-col :span="8">
            <span v-text="entTaxOfficeName"></span>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-dialog
        title="编辑企业信息"
        :visible.sync="dialogVisible"
        center
        v-on:close="callFindEntInfoByCurrentEnt"
    >
      <div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span style="color: red">*</span>
            <span>企业类型：</span>
            <el-select
                v-model="entType"
                placeholder="请选择"
                disabled="disabled"
            >
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="flex: 1">
            <span style="color: red">*</span>
            <span>企业简称：</span>
            <el-input
                v-model="entShortName"
                placeholder="请输入企业简称"
                class="ent_input"
            ></el-input>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span style="color: red">*</span>
            <span>企业地址：</span>
            <el-input
                v-model="entAddress"
                placeholder="请输入企业地址"
                class="ent_input"
            ></el-input>
          </div>
          <div style="flex: 1">
            <span>企业联系人：</span>
            <el-input
                v-model.trim="entContactPerson"
                placeholder="请输入企业联系人"
                class="ent_input"
            ></el-input>
            <br/>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span>企业电话：</span>
            <el-input
                v-model="entPhone"
                placeholder="请输入企业电话"
                class="ent_input"
            ></el-input>
            <br/>
          </div>
          <div style="flex: 1">
            <span>银行名称：</span>
            <el-input
                v-model="bankName"
                placeholder="请输入银行户名"
                class="ent_input"
            ></el-input>
            <br/>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span>银行账号：</span>
            <el-input
                v-model="bankAccountNumber"
                placeholder="请输入银行账号"
                class="ent_input"
            ></el-input>
            <br/>
          </div>
          <div style="flex: 1">
            <span>收款人：</span>
            <el-input
                v-model.trim="payees"
                placeholder="请输入收款人"
                class="ent_input"
            ></el-input>
            <br/>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span>审核者：</span>
            <el-input
                v-model.trim="reviewers"
                placeholder="请输入审核者"
                class="ent_input"
            ></el-input>
          </div>
          <div style="flex: 1">
            <span>开票人员：</span>
            <el-input
                v-model.trim="drawers"
                placeholder="请输入开票人员"
                class="ent_input"
            ></el-input>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <!-- <span style="color: red">*</span> -->
            <span>可用税率：</span>
            <el-select
                v-model="entTax"
                placeholder="请选择可用税率"
                multiple
                disabled
                style="width: 200px"
            >
              <el-option
                  v-for="(_, i) in entTaxModal"
                  :label="entTaxModal[i].label"
                  :value="entTaxModal[i].value"
                  :key="i"
              ></el-option>
            </el-select>
            <el-button
                style="margin-left: 10px"
                @click="handleSyncSkRates"
            >同步税率
            </el-button
            >
          </div>
          <div style="flex: 1">
            <span>开票默认商品税率（%）：</span>
            <el-input-number
                v-model="defaultTaxRate"
                :precision="0"
                :step="1"
                :max="10000"
                :controls="false"
            ></el-input-number>
          </div>
        </div>
        <div class="edit_layout">
          <div style="flex: 1">
            <span style="color: red">*</span>
            <span>默认开票设备：</span>
            <el-select
                v-model="defaultInvoiceDevice"
                placeholder="请选择"
            >
              <el-option
                  v-for="item in deviceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="edit_layout" style="justify-content: center">
          <span style="font-size: 10px; color: red">注意：</span>
          <span style="font-size: 10px"
          >输入多个开票人、收款人和审核者时，请以英文逗号进行分隔（例：张三,王武）</span
          >
        </div>
      </div>
      <div slot="footer" class="customer">
        <el-button
            class="invoice_button"
            v-on:click="dialogVisible = false"
        >取 消
        </el-button
        >
        <el-button
            class="invoice_button"
            type="primary"
            v-on:click="entEditSave"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { FindEntInfoByCurrentEnt, syncSkRates } from '@/api/ent_info'
import { GetDeviceLabel } from '@/api/ent_device'
import { AxiosRequestData } from '@/data/axios_request'
import cache from '@/utils/cache'

// 企业类型列表
const entTypes = [
  {
    value: 1,
    label: '一般纳税人',
  },
  {
    value: 2,
    label: '小规模纳税人',
  },
  {
    value: 3,
    label: '起征点以下纳税人',
  },
]

// 设备类型列表
const deviceTypes = [
  {
    value: 1,
    label: '软证书',
  },
  {
    value: 2,
    label: '税控盘',
  },
  {
    value: 3,
    label: '金税盘',
  },
  {
    value: 4,
    label: '税控UKey',
  },
  {
    value: 5,
    label: '税控服务器',
  },
]

export default {
  name: 'CurrentEntInfo',
  data() {
    return {
      loading: false,
      entName: '',
      entShortName: '',
      entTaxId: '',
      bankName: '',
      entType: '',
      bankAccountNumber: '',
      entAddress: '',
      payees: '',
      entPhone: '',
      reviewers: '',
      entContactPerson: '',
      availableTaxes: '',
      defaultTaxRate: '', // 开票默认商品税率
      defaultInvoiceDevice: '',
      drawers: '',
      dialogVisible: false,
      options: [
        {
          value: 1,
          label: '一般纳税人',
        },
        {
          value: 2,
          label: '小规模纳税人',
        },
        {
          value: 3,
          label: '起征点以下纳税人',
        },
      ],
      entTaxModal: [],
      token: '',
      account: '',
      deviceList: [],
      entTax: [],
      defaultInvoiceDeviceKey: '',
      entTaxOfficeCode: '',
      entTaxOfficeName: ''
    }
  },
  created() {
    this.token = cache.getToken()
    let user = JSON.parse(cache.getSession('user'))
    this.account = user.account
    this.callFindEntInfoByCurrentEnt()
  },
  computed: {
    fmtEntType: function () {
      let result = this.entType
      for (const item of entTypes) {
        if (item.value == this.entType) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtDefaultInvoiceDevice: function () {
      let result = this.defaultInvoiceDevice
      for (const item of deviceTypes) {
        if (item.value == this.defaultInvoiceDevice) {
          result = item.label
          break
        }
      }
      return result
    },
  },
  methods: {
    // 刷新
    handleRefresh() {
      this.callFindEntInfoByCurrentEnt()
    },
    // 根据用户当前选中的税号查询企业信息
    callFindEntInfoByCurrentEnt() {
      let _this = this
      _this.loading = true
      FindEntInfoByCurrentEnt()
          .then((val) => {
            _this.loading = false
            _this.entName = val.data.entName
            _this.entShortName = val.data.entShortName
            _this.entTaxId = val.data.entTaxId
            _this.bankName = val.data.bankName
            _this.entType = val.data.entType
            _this.bankAccountNumber = val.data.bankAccountNumber
            _this.entAddress = val.data.entAddress
            _this.payees = val.data.payees
            _this.entPhone = val.data.entPhone
            _this.reviewers = val.data.reviewers
            _this.entContactPerson = val.data.entContactPerson
            _this.availableTaxes = val.data.availableTaxes
            _this.drawers = val.data.drawers
            _this.entTaxOfficeCode = val.data.entTaxOfficeCode
            _this.entTaxOfficeName = val.data.entTaxOfficeName

            const tempDefaultTaxRate = val.data.defaultTaxRate
            if (tempDefaultTaxRate && !isNaN(tempDefaultTaxRate)) {
              _this.defaultTaxRate = tempDefaultTaxRate * 100
            } else {
              _this.defaultTaxRate = 0
            }
            if (
                val.data.availableTaxes !== '' ||
                val.data.availableTaxes != null
            ) {
              _this.entTax = val.data.availableTaxes.split(',')
            }
            _this.defaultInvoiceDevice = GetDeviceLabel(
                val.data.defaultInvoiceDevice
            )
            _this.defaultInvoiceDeviceKey =
                val.data.defaultInvoiceDevice
          })
          .catch((err) => {
            _this.loading = false
            _this.$message.error(err)
          })
    },
    // 编辑企业信息
    showEditCompany() {
      this.getTaxRate()
      this.getInvoiceDevice()
      this.dialogVisible = true
    },
    // 获取企业税率
    async getTaxRate() {
      if (this.account && this.token) {
        const url = '/auth/param/getRates'
        let response = await AxiosRequestData(url, null, {}, false, 2)
        if (response) {
          if (response.code === 0) {
            this.entTaxModal = response.data
          }
        }
      }
    },
    // 获取企业设备列表
    async getInvoiceDevice() {
      if (this.account && this.token) {
        const url = '/sys/entDevice/findDevices'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              entTaxId: this.entTaxId,
            },
            false,
            2
        )
        if (response) {
          if (response.code === 0) {
            this.deviceList = []
            let device = {}
            response.data.map((_, i) => {
              device = {
                value: response.data[i].deviceKey,
                label: response.data[i].deviceLabel,
              }
              this.deviceList = this.deviceList.concat(device)
            })
          }
        }
      }
    },
    // 编辑企业信息
    async entEditSave() {
      let taxRate = ''
      if (this.entType === '' || this.entType == null) {
        this.$message({
          message: '企业类型不能为空！',
          type: 'warning',
        })
        return
      }
      if (this.entShortName === '' || this.entShortName == null) {
        this.$message({
          message: '企业简称不能为空！',
          type: 'warning',
        })
        return
      } else {
        if (this.entShortName.length > 9) {
          this.$message({
            message: '企业简称长度不能大于9为字符！',
            type: 'warning',
          })
          return
        }
      }
      if (this.entAddress === '' || this.entAddress == null) {
        this.$message({
          message: '企业地址不能为空！',
          type: 'warning',
        })
        return
      }
      // if (this.entTax.length <= 0) {
      //     this.$message({
      //         message: "企业可用税率不能为空！",
      //         type: "warning",
      //     });
      //     return;
      // } else {
      //     taxRate = this.entTax.join(",");
      // }
      taxRate = this.entTax.join(',')
      let tempDefaultTaxRate = ''
      if (this.defaultTaxRate && !isNaN(this.defaultTaxRate)) {
        tempDefaultTaxRate = this.defaultTaxRate / 100
      }
      let args = {
        entTaxId: this.entTaxId,
        entName: this.entName,
        entType: this.entType,
        entAddress: this.entAddress,
        availableTaxes: taxRate,
        entContactPerson: this.entContactPerson,
        entPhone: this.entPhone,
        bankName: this.bankName,
        bankAccountNumber: this.bankAccountNumber,
        payees: this.payees,
        reviewers: this.reviewers,
        reqChannel: 4,
        mobile: this.account,
        entShortName: this.entShortName,
        defaultInvoiceDevice: this.defaultInvoiceDeviceKey,
        drawers: this.drawers,
        defaultTaxRate: tempDefaultTaxRate,
      }
      console.log('编辑企业信息 参数：')
      console.log(args)
      if (this.account && this.token) {
        const url = '/sys/entInfo/updateBriefInfo'
        let response = await AxiosRequestData(
            url,
            this.token,
            args,
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.dialogVisible = false
            this.callFindEntInfoByCurrentEnt()
            // await this.getDefaultCompany()
            this.$message({
              message: '企业信息编辑成功！',
              type: 'success',
            })
          } else {
            this.$message.error('企业信息编辑失败！')
            this.dialogVisible = false
          }
        }
      }
    },
    // 企业同步税率
    handleSyncSkRates() {
      let _this = this
      syncSkRates()
          .then((val) => {
            _this.$message.success('同步税率操作：' + val.msg)
            _this.entTax = val.data.rates.split(',')
          })
          .catch((err) => {
            _this.$message.error(err)
          })
          .finally(() => {
          })
    },
  },
}
</script>

<style scoped>
.ent_input {
  width: 250px;
}

.edit_layout {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
</style>
