<template>
    <div id="enterprise_information" class="body">
        <div style="height: 50px">
            <el-row type="flex" :gutter="20">
                <el-col :span="5">
                    <el-input
                        v-model="searchEntName"
                        clearable
                        prefix-icon="el-icon-search"
                        placeholder="请输入企业税号"
                        class="ent_input"
                    ></el-input>
                </el-col>
                <el-col :span="6">
                    <el-input
                        v-model="searchEntTaxId"
                        clearable
                        prefix-icon="el-icon-search"
                        placeholder="请输入企业名称"
                        class="ent_input"
                    ></el-input>
                </el-col>
                <el-col :span="16">
                    <el-button v-on:click="getEntList" type="primary"
                        >搜索</el-button
                    >
                </el-col>
            </el-row>
        </div>
        <div style="flex: 1">
            <el-container>
                <el-table
                    :data="entList"
                    border
                    style="width: 100%; flex: 1"
                    :height="tableHeight"
                    ref="table"
                >
                    <el-table-column
                        prop="entName"
                        label="企业名称"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="entTaxId"
                        label="企业税号"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="entShortName"
                        label="企业简称"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="entType"
                        label="企业类型"
                        width="100"
                        :formatter="getEntType"
                    ></el-table-column>
                    <el-table-column
                        prop="entAddress"
                        label="企业地址"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="entContactPerson"
                        label="企业联系人"
                        width="100"
                    ></el-table-column>
                    <el-table-column
                        prop="entPhone"
                        label="企业电话"
                        width="120"
                    ></el-table-column>
                    <el-table-column
                        prop="entTaxOfficeCode"
                        label="企业税局"
                        width="120"
                    ></el-table-column>
                    <el-table-column
                        prop="serviceStatus"
                        label="企业服务状态"
                        width="120"
                        :formatter="getServerStatus"
                    ></el-table-column>
                    <el-table-column
                        prop="availableTaxes"
                        label="可用税率"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="defaultTaxRate"
                        label="开票默认商品税率"
                        width="140"
                    ></el-table-column>
                    <el-table-column
                        prop="bankAccountName"
                        label="银行"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="bankAccountNumber"
                        label="银行账号"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="payees"
                        label="收款人"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="reviewers"
                        label="审核者"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        prop="drawers"
                        label="开票人"
                        width="160"
                    ></el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        align="center"
                        width="120"
                    >
                        <template slot-scope="scope">
                            <el-button
                                @click="entEdit(scope.row)"
                                type="primary"
                                size="small"
                                >编辑</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-container>
        </div>
        <div style="height: 50px">
            <el-row type="flex" :gutter="20">
                <el-col :span="12"></el-col>
                <el-col :span="12">
                    <div style="text-align: right">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pageNum"
                            :page-sizes="pageSizes"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next"
                            :total="totalNumber"
                        ></el-pagination>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-dialog title="编辑企业信息" :visible.sync="dialogVisible" center>
            <div>
                <div class="edit_layout">
                    <div style="flex: 1">
                        <span style="color: red">*</span>
                        <span>企业类型：</span>
                        <el-select
                            v-model="entType"
                            disabled
                            placeholder="请选择"
                        >
                            <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="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="entBankName"
                            placeholder="请输入银行户名"
                            class="ent_input"
                        ></el-input>
                        <br />
                    </div>
                </div>
                <div class="edit_layout">
                    <div style="flex: 1">
                        <span>银行账号：</span>
                        <el-input
                            v-model="entBankAccount"
                            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 { AxiosRequestData } from "../../data/axios_request";
import cache from "@/utils/cache";

import { syncSkRates } from "@/api/ent_info";

export default {
    name: "enterprise_information",
    data() {
        return {
            searchEntName: "",
            searchEntTaxId: "",
            dialogVisible: false,
            account: "",
            token: "",
            entList: [],
            pageNum: 1,
            pageSize: 10,
            totalNumber: 0,
            totalPage: 0,
            pageSizes: [10, 30, 50, 100],
            entType: "",
            entTax: [],
            entTaxModal: [],
            entAddress: "",
            entContactPerson: "",
            entPhone: "",
            entBankName: "",
            entBankAccount: "",
            payees: "",
            reviewers: "",
            entName: "",
            entTaxId: "",
            entShortName: "",
            options: [
                {
                    value: 1,
                    label: "一般纳税人",
                },
                {
                    value: 2,
                    label: "小规模纳税人",
                },
                {
                    value: 3,
                    label: "起征点以下纳税人",
                },
            ],
            defaultInvoiceDevice: "",
            deviceList: [],
            drawers: "",
            defaultTaxRate: "", //开票默认商品税率
            tableHeight: "",
        };
    },
    created() {
        this.tableHeight = window.innerHeight - 250;
        let user = JSON.parse(cache.getSession("user"));
        this.account = user.account;
        this.token = cache.getToken();
        this.getEntList();
    },
    mounted() {
        this.tableHeight = window.innerHeight - 250;
        window.onresize = () => {
            return (() => {
                this.tableHeight = window.innerHeight - 250;
            })();
        };
    },
    methods: {
        // pageIndex(index) {
        //     let currentPage = this.search.resultPagination.currentPage;   //当前页码，具体看组件取值
        //     let pageSize = this.search.resultPagination.pageSize;    //每页条数，具体是组件取值
        //     return (index + 1) + (currentPage - 1) * pageSize;
        // },
        // 获取企业类型
        getEntType(row, column, cellValue) {
            if (cellValue == 1) {
                return "一般纳税人";
            }
            if (cellValue == 2) {
                return "小规模纳税人";
            }
            if (cellValue == 3) {
                return "起征点以下纳税人";
            } else {
                return "";
            }
        },
        // 获取企业的服务状态
        getServerStatus(row, column, cellValue) {
            if (cellValue == 1) {
                return "待初始化";
            }
            if (cellValue == 2) {
                return "初始化成功";
            }
            if (cellValue == 3) {
                return "服务状态有效";
            }
            if (cellValue == 4) {
                return "欠费";
            } else {
                return "";
            }
        },
        // 编辑企业信息
        entEdit(row) {
            this.dialogVisible = true;
            this.deviceList = [];
            this.getInvoiceDevice(row);
            this.getTaxRate();
            this.entName = row.entName;
            this.entTaxId = row.entTaxId;
            this.entType = row.entType;
            this.entAddress = row.entAddress;
            if (row.availableTaxes !== "" || row.availableTaxes != null) {
                // this.entTaxModal = row.availableTaxes.split(',')
                this.entTax = row.availableTaxes.split(",");
            }
            this.entContactPerson = row.entContactPerson;
            this.entPhone = row.entPhone;
            this.entBankName = row.bankName;
            this.entBankAccount = row.bankAccountNumber;
            this.payees = row.payees;
            this.reviewers = row.reviewers;
            this.entShortName = row.entShortName;
            this.defaultInvoiceDevice = row.defaultInvoiceDevice;
            this.drawers = row.drawers;
            const tempDefaultTaxRate = row.defaultTaxRate;
            if (tempDefaultTaxRate && !isNaN(tempDefaultTaxRate)) {
                this.defaultTaxRate = tempDefaultTaxRate * 100;
            } else {
                this.defaultTaxRate = 0;
            }
        },
        // 变更每页显示的数据条数
        handleSizeChange(val) {
            this.pageSize = val;
            this.getEntList();
        },
        // 翻页
        handleCurrentChange(val) {
            this.pageNum = val;
            this.getEntList();
        },
        // 获取企业列表信息
        async getEntList() {
            if (this.account && this.token) {
                const url = "/sys/entInfo/findPageByMobile";
                let response = await AxiosRequestData(
                    url,
                    this.token,
                    {
                        entName: this.searchEntName,
                        entTaxId: this.searchEntTaxId,
                        userMobile: this.account,
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        reqChannel: 4,
                    },
                    false,
                    2
                );
                if (response) {
                    if (response.code === 0) {
                        this.totalNumber = response.data.total;
                        this.totalPage = response.data.pages;
                        this.entList = response.data.records;
                    }
                }
            }
        },
        // 修改企业信息
        async entEditSave() {
            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;
            }
            let taxRate = this.entTax.join(",");
            // if (this.entTax.length <= 0) {
            //     this.$message({
            //         message: "企业可用税率不能为空！",
            //         type: "warning",
            //     });
            //     return;
            // } else {
            //     taxRate = this.entTax.join(",");
            // }

            let tempDefaultTaxRate = "";
            if (this.defaultTaxRate && !isNaN(this.defaultTaxRate)) {
                tempDefaultTaxRate = this.defaultTaxRate / 100;
            }
            if (this.account && this.token) {
                const url = "/sys/entInfo/updateBriefInfo";
                let response = await AxiosRequestData(
                    url,
                    this.token,
                    {
                        entTaxId: this.entTaxId,
                        entName: this.entName,
                        entType: this.entType,
                        entAddress: this.entAddress,
                        availableTaxes: taxRate,
                        entContactPerson: this.entContactPerson,
                        entPhone: this.entPhone,
                        bankName: this.entBankName,
                        bankAccountNumber: this.entBankAccount,
                        payees: this.payees,
                        reviewers: this.reviewers,
                        reqChannel: 4,
                        mobile: this.account,
                        entShortName: this.entShortName,
                        defaultInvoiceDevice: this.defaultInvoiceDevice,
                        drawers: this.drawers,
                        defaultTaxRate: tempDefaultTaxRate,
                    },
                    false,
                    1
                );
                if (response) {
                    if (response.code === 0) {
                        await this.getDefaultCompany();
                        this.$message({
                            message: "企业信息编辑成功！",
                            type: "success",
                        });
                        this.dialogVisible = false;
                        await this.getEntList();
                        location.reload();
                    } else {
                        this.$message.error("企业信息编辑失败！");
                        this.dialogVisible = false;
                    }
                }
            }
        },
        // 获取默认企业信息
        async getDefaultCompany() {
            if (this.account && this.token) {
                const url = "/auth/comm/user/findDefaultChoose";
                let response = await AxiosRequestData(
                    url,
                    this.token,
                    {
                        mobile: this.account,
                    },
                    false,
                    2
                );
                if (response) {
                    if (response.code === 0) {
                        this.companyName = response.data.entName;
                        cache.setSession("company", response.data);
                    }
                }
            }
        },
        // 获取企业设备列表
        async getInvoiceDevice(row) {
            if (this.account && this.token) {
                const url = "/sys/entDevice/findDevices";
                let response = await AxiosRequestData(
                    url,
                    this.token,
                    {
                        entTaxId: row.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 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;
                    }
                }
            }
        },
        // 企业同步税率
        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>
.body {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.ent_input {
    width: 250px;
}

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