<template>
  <div class="deedtax">
    <div class="search-wrapper">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search_form"
        style="text-align: left"
      >
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            @keyup.enter.native="onSubmit"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号码"
            @keyup.enter.native="onSubmit"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="不动产坐落辖市区"
          v-if="
            this.realEstateArea == '市区' ||
            (this.searchForm.departmentCode == '10000032' &&
              this.realEstateArea != '句容市')
          "
        >
          <el-select
            v-model="searchForm.checkArealEstateArea"
            placeholder="请选择不动产坐落辖市区"
            @change="onSubmit"
            size="medium"
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-if="
              this.searchForm.departmentCode == '10000033' ||
              this.searchForm.departmentCode == '10000031'
            "
            @click="downLoadShow = true"
            >导出
          </el-button>
        </el-form-item>
        <br />
        <el-form-item label="状态" style="margin-top: 10px">
          <el-radio-group v-model="searchForm.state" @change="onSubmit">
            <el-radio
              :label="item.state"
              v-for="item in stateList"
              :key="item.state"
              >{{ item.stateName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-wrapper">
      <table-template
        :tableData="tableData"
        :tableColumns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        @Jump="jumpPage"
      >
        <el-table-column slot="departmentName" label="实施主体" align="center">
          <template>
            {{ this.$route.query.departmentName }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.reviewerState == 0"
              >待审核</el-tag
            >
            <el-tag type="success" v-if="scope.row.reviewerState == 8"
              >初审通过</el-tag
            >
            <!-- <el-tag type="warning" v-if="scope.row.state == 1">待复审</el-tag>
            <el-tag type="warning" v-if="scope.row.state == 2">待用户确认</el-tag>
            <el-tag type="warning" v-if="scope.row.state == 3">待退税办理</el-tag> -->
            <el-tag type="danger" v-if="scope.row.reviewerState == 9"
              >已驳回</el-tag
            >
            <!-- <el-tag type="info" v-if="scope.row.state == 5">已撤销</el-tag> -->
            <!-- <el-tag type="warning" v-if="scope.row.state == 6">资料审核</el-tag> -->
            <!-- <el-tag type="success" v-if="scope.row.state == 6">已完成</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="350" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" round @click="view(scope.row)"
              >查看</el-button
            >
            <el-button
              type="primary"
              size="mini"
              round
              @click="record(scope.row)"
              >记录</el-button
            >
            <!-- 申请的单子有通过拒绝-->
            <el-button
              v-if="scope.row.reviewerState == 0 && scope.row.state == 0"
              type="success"
              size="mini"
              round
              @click="pass(scope.row)"
              >通过
            </el-button>
            <el-button
              v-if="scope.row.reviewerState == 0 && scope.row.state == 0"
              type="danger"
              size="mini"
              round
              @click="deny(scope.row)"
              >拒绝
            </el-button>
            <el-button
              v-if="
                (scope.row.reviewerState == 9 && scope.row.state == 4) ||
                ((scope.row.state == 0 || scope.row.state == 1) &&
                  scope.row.reviewerState == 8)
              "
              type="info"
              size="mini"
              round
              @click="drevokeeny(scope.row)"
              >撤销
            </el-button>
            <el-button
              v-if="scope.row.state == 0 && realEstateArea !== '丹阳市'"
              type="warning"
              size="mini"
              round
              @click="reassignment(scope.row)"
              >改派
            </el-button>
          </template>
        </el-table-column>
      </table-template>
    </div>
    <el-dialog
      title="申报详情"
      :visible.sync="viewShow"
      width="800px"
      :close-on-press-escape="false"
    >
      <div class="content">
        <!-- 新增功能start -->
        <el-table :data="totalList" style="width: 100%">
          <el-table-column prop="departmentName" label="审核单位" width="180">
          </el-table-column>
          <el-table-column prop="state" label="审核状态" width="180">
          </el-table-column>
          <el-table-column prop="reason" label="审核意见"> </el-table-column>
          <el-table-column prop="createTime" label="审核时间">
          </el-table-column>
        </el-table>
        <div class="cell" v-if="viewDetail.checkArea != '丹阳市'">
          <p class="label">是否享受过相关政策</p>
          <p
            :class="[
              'value',
              viewDetail.enjoyFlag == true ? 'value2' : 'value1',
            ]"
          >
            {{ viewDetail.enjoyFlag ? "否" : "是" }}
          </p>
        </div>
        <!-- 新增功能end -->
        <div class="cell">
          <p class="label">事项名称</p>
          <p class="value">{{ viewDetail.guideName }}</p>
        </div>
        <div class="cell">
          <p class="label">实施主体</p>
          <p class="value">{{ this.$route.query.departmentName }}</p>
        </div>
        <div class="cell">
          <p class="label">姓名</p>
          <p class="value">{{ viewDetail.name }}</p>
        </div>
        <div class="cell">
          <p class="label">身份证</p>
          <p class="value">{{ viewDetail.idCard }}</p>
        </div>
        <div class="cell">
          <p class="label">手机号</p>
          <p class="value">{{ viewDetail.phone }}</p>
        </div>
        <div class="cell">
          <p class="label">辖市区</p>
          <p class="value">{{ viewDetail.userArea }}</p>
        </div>
        <div class="cell">
          <p class="label">联系地址</p>
          <p class="value">{{ viewDetail.address }}</p>
        </div>
        <div class="cell">
          <p class="label">身份证照片</p>
          <p class="value">
            <el-image
              v-for="(item, index) in viewDetail.idCardPicture"
              :key="index"
              style="width: 100px; height: 100px; margin-right: 10px"
              :src="item.picture"
              :z-index="7777777"
              :preview-src-list="[item.picture]"
            >
            </el-image>
          </p>
        </div>
        <div class="cell">
          <p class="label">所属银行</p>
          <p class="value">{{ viewDetail.bank }}</p>
        </div>
        <div class="cell">
          <p class="label">银行卡号</p>
          <p class="value">{{ viewDetail.bankCard }}</p>
        </div>
        <div class="cell">
          <p class="label">银行卡照片</p>
          <p class="value">
            <el-image
              v-for="(item, index) in viewDetail.bankCardPicture"
              :key="index"
              style="width: 100px; height: 100px; margin-right: 10px"
              :src="item.picture"
              :z-index="7777777"
              :preview-src-list="[item.picture]"
            >
            </el-image>
          </p>
        </div>
        <div class="cell">
          <p class="label">契税发票号码</p>
          <p
            class="value"
            v-if="viewDetail.deedBillCode && !viewDetail.secondDeedBillCode"
          >
            NO.{{ viewDetail.deedBillCode }}
          </p>
          <p
            class="value"
            v-if="!viewDetail.deedBillCode && viewDetail.secondDeedBillCode"
          >
            NO.{{ viewDetail.secondDeedBillCode }}
          </p>
          <p
            class="value"
            v-if="viewDetail.deedBillCode && viewDetail.secondDeedBillCode"
          >
            NO.{{ viewDetail.deedBillCode }}、NO.{{
              viewDetail.secondDeedBillCode
            }}
          </p>
        </div>
        <div class="cell">
          <p class="label">缴纳契税金额(元)</p>
          <p class="value">{{ viewDetail.paymentDeedTaxAmount }}</p>
        </div>
        <div class="cell" v-if="viewDetail.taxReimbursementAmount">
          <p class="label">退税金额(万元)</p>
          <p class="value">{{ viewDetail.taxReimbursementAmount }}</p>
        </div>
        <div class="cell">
          <p class="label">房屋面积</p>
          <p class="value">{{ viewDetail.square }}</p>
        </div>
        <div class="cell">
          <p class="label">不动产坐落辖市区</p>
          <p class="value">{{ viewDetail.checkArea }}</p>
        </div>
        <div class="cell">
          <p class="label">网签时间</p>
          <p class="value">{{ viewDetail.netSignTime }}</p>
        </div>
        <div class="cell">
          <p class="label">不动产权证号</p>
          <p class="value">{{ viewDetail.realEstateCard }}</p>
        </div>
        <div class="cell">
          <p class="label">房屋属性</p>
          <p class="value">
            {{
              viewDetail.houseType == 1
                ? "商品房"
                : viewDetail.houseType == 2
                ? "二手房"
                : viewDetail.houseType == 3
                ? "商办用房"
                : "-"
            }}
          </p>
        </div>
        <div class="cell">
          <p class="label">不动产权坐落地址</p>
          <p class="value">{{ viewDetail.realEstateAddress }}</p>
        </div>
        <div class="cell">
          <p class="label">不动产权证书</p>
          <p class="value">
            <el-image
              v-for="(item, index) in viewDetail.certificate"
              :key="index"
              style="width: 100px; height: 100px; margin-right: 10px"
              :src="item.picture"
              :z-index="7777777"
              :preview-src-list="[item.picture]"
            >
            </el-image>
          </p>
        </div>
        <div class="cell">
          <p class="label">商品房买卖合同3张</p>
          <p class="value">
            <el-image
              v-for="(item, index) in viewDetail.contract"
              :key="index"
              style="width: 100px; height: 100px; margin-right: 10px"
              :src="item.picture"
              :z-index="7777777"
              :preview-src-list="[item.picture]"
            >
            </el-image>
          </p>
        </div>
        <div class="cell">
          <p class="label">契税完税凭证</p>
          <p class="value">
            <el-image
              v-for="(item, index) in viewDetail.voucher"
              :key="index"
              style="width: 100px; height: 100px; margin-right: 10px"
              :src="item.picture"
              :z-index="7777777"
              :preview-src-list="[item.picture]"
            >
            </el-image>
          </p>
        </div>
        <div class="cell" v-if="viewDetail.commitmentType">
          <p class="label">共有情况</p>
          <p class="value">
            <span v-if="viewDetail.commitmentType == 1"
              >单独所有、共同共有</span
            >
            <span v-if="viewDetail.commitmentType == 2">按份共有</span>
          </p>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="操作记录"
      :visible.sync="recordShow"
      width="800px"
      :close-on-press-escape="false"
    >
      <div class="content" v-if="recordList[0]">
        <div class="cell" v-for="(item, index) in recordList" :key="index">
          <p class="label" style="margin-right: 20px">
            {{ item.stateName }}
            <span v-if="item.reason">({{ item.reason }})</span>
          </p>
          <div class="info">
            <p class="item">操作人：{{ item.departmentName }}</p>
            <p class="item">操作时间：{{ item.createTime }}</p>
          </div>
        </div>
        <p v-if="record.length === 0">暂无记录~</p>
      </div>
    </el-dialog>
    <el-dialog
      title="改派部门"
      :visible.sync="reassignmentShow"
      width="600px"
      :close-on-press-escape="false"
      :before-close="closeDialog"
    >
      <el-form label-width="120px" :model="params">
        <el-row>
          <el-form-item label="改派部门">
            <el-cascader
              v-model="params.checkArea"
              placeholder="请选择部门"
              :options="checkAreaList"
              :show-all-levels="false"
              @change="handleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="determine">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="导出范围"
      :visible.sync="downLoadShow"
      width="600px"
      :close-on-press-escape="false"
    >
      <el-form label-width="120px" :model="params">
        <el-row>
          <el-form-item label="状态">
            <el-select v-model="downLoadParams.state" placeholder="请选择状态">
              <el-option
                v-for="item in downLoadList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
              v-model="date"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="time"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedownLoad">取 消</el-button>
        <el-button type="primary" @click="downLoad">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableTemplate from "@/components/Table";
import { changeList, setName, setTel, setCertNo } from "@/utils";
import {
  queryCommerListDeedTaxFromInitDepartment,
  queryCommerDeedTaxDetailInfo,
  queryCommerDeedTaxRecord,
  updateCommerInitDepartmentState,
  initCommerDepartmentRevocation,
  updateCommerCheckArea,
  saveCommerFileUrl,
  userCommerExport,
} from "@/api/commercial.js";
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { uploadWordFile } from "@/api/upload";
import { downFile } from "@/utils/common.js";
// import { getTempUrl } from "@/api/exportFileUrl";

export default {
  components: { TableTemplate },
  data() {
    return {
      userName: "",
      searchForm: {
        name: "",
        phone: "",
        state: "",
        departmentCode: "",
        checkArealEstateArea: "",
      },
      stateList: [
        {
          state: "",
          stateName: "全部",
          type: "",
        },
        {
          state: 0,
          stateName: "待审核",
          type: "warning",
        },
        {
          state: 8,
          stateName: "初审通过",
          type: "success",
        },
        {
          state: 9,
          stateName: "已驳回",
          type: "danger",
        },
      ],
      stateList1: [
        {
          state: 0,
          stateName: "待审核",
          type: "warning",
        },
        {
          state: 1,
          stateName: "待复审",
          type: "warning",
        },
        {
          state: 6,
          stateName: "已完成",
          type: "warning",
        },
        {
          state: 2,
          stateName: "资料审核",
          type: "warning",
        },
        {
          state: 3,
          stateName: "卡号确认",
          type: "success",
        },
        {
          state: 4,
          stateName: "已驳回",
          type: "danger",
        },
        {
          state: 8,
          stateName: "初审通过",
          type: "success",
        },
        {
          state: 9,
          stateName: "已驳回",
          type: "danger",
        },
      ],
      loading: false,
      tableData: [],
      tableColumns: [
        {
          key: "code",
          label: "申请编号",
          width: 200,
        },
        {
          key: "name",
          label: "企业联系人",
          width: 150,
        },
        {
          key: "phone",
          label: "手机号",
          width: 150,
        },
        {
          key: "guideName",
          label: "事项名称",
          width: 150,
        },
        {
          key: "realEstateArea",
          label: "不动产坐落辖市区",
          width: 150,
        },
        {
          key: "departmentName",
          label: "实施主体",
          type: "slot",
          // width: 150
        },
        {
          key: "createTime",
          label: "更新时间",
          width: 160,
        },
      ],
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      areaList: [
        {
          id: "",
          label: "全部",
        },
        {
          id: "京口区",
          label: "京口区",
        },
        {
          id: "润州区",
          label: "润州区",
        },
        {
          id: "丹徒区",
          label: "丹徒区",
        },
        {
          id: "镇江新区-大港片区",
          label: "镇江新区-大港片区",
        },
        {
          id: "镇江新区-丁卯片区",
          label: "镇江新区-丁卯片区",
        },
        {
          id: "镇江高新区",
          label: "镇江高新区",
        },
        {
          id: "句容市",
          label: "句容市",
        },
      ],
      realEstateArea: null,
      departmentName: "",
      downLoadShow: false,
      viewShow: false,
      viewDetail: {},
      recordShow: false,
      recordList: [],
      examineList: [], // 审核单位数据
      housingList: [], // 住建局列表数据
      totalList: [], // 合并数组
      realName: "",
      reassignmentShow: false,
      params: {
        code: "",
        checkArea: "",
        departmentCode: "10000031",
      },
      checkAreaList: [
        {
          label: "市区",
          value: "市区",
          children: [
            {
              label: "京口区",
              value: "京口区",
            },
            {
              label: "润州区",
              value: "润州区",
            },
            {
              label: "镇江高新区",
              value: "镇江高新区",
            },
            {
              label: "镇江新区-丁卯片区",
              value: "镇江新区-丁卯片区",
            },
          ],
        },
        {
          label: "丹徒区",
          value: "丹徒区",
        },
        {
          label: "镇江新区",
          value: "镇江新区",
          children: [
            {
              label: "大港片区",
              value: "大港片区",
            },
          ],
        },
        {
          label: "句容市",
          value: "句容市",
        },
        // {
        //   label: "丹阳市",
        //   value: "丹阳市",
        // },
      ],

      // 以下是填充模板字段
      detail: {},
      arrList: [],
      arr1: "",
      arr2: "",
      arr3: "",
      downLoadParams: {
        state: "",
        checkArea: this.$route.query.realEstateArea,
        begTime: "",
        departmentCode: this.$route.query.departmentCode,
        endTime: "",
      },
      downLoadList: [
        {
          label: "全部",
          value: "null",
        },
        {
          label: "待审核",
          value: "0",
        },
        {
          label: "初审通过",
          value: "8",
        },
        {
          label: "已驳回",
          value: "9",
        },
      ],
      date: "",
      docxsrc: "",
      rowDetail: "",
    };
  },
  watch: {
    $route() {
      if (this.$route) {
        this.userName = localStorage.getItem("userName");
        // 10000031  财政局code   10000032 税务局code    10000033  不动产登记中心code
        this.searchForm.departmentCode = this.$route.query.departmentCode;
        this.realEstateArea = this.$route.query.realEstateArea
          ? this.$route.query.realEstateArea
          : null;
        // departmentName: 审核部门名称（左侧列表）
        this.departmentName = this.$route.query.departmentName;
        this.searchForm.name = "";
        this.searchForm.phone = "";
        this.searchForm.state = "";
        this.init();
      }
    },
  },
  methods: {
    init() {
      this.tableData = [];
      this.loading = true;
      let parmas = {
        name: this.searchForm.name,
        phone: this.searchForm.phone,
        state: this.searchForm.state,
        departmentCode: this.searchForm.departmentCode,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        checkArea: this.realEstateArea,
        checkArealEstateArea: this.searchForm.checkArealEstateArea,
      };
      queryCommerListDeedTaxFromInitDepartment(parmas).then((res) => {
        this.loading = false;
        // console.log(res.data)
        if (res.success) {
          this.pagination.total = res.data.total;
          if (res.data.total) {
            this.tableData = res.data.list.map((item) => {
              item.stateName = this.getSatusArr(item.reviewerState).stateName;
              item.type = this.getSatusArr(item.reviewerState).type;
              return item;
            });
            if (localStorage.getItem("userName") == "admin") {
              this.tableData = changeList(this.tableData);
            }
          } else {
            this.tableData = [];
          }
        }
      });
    },
    getSatusArr(state) {
      return this.stateList.filter((item) => {
        return item.state == state;
      })[0];
    },
    onSubmit() {
      this.pagination.currentPage = 1;
      this.init();
    },
    jumpPage() {
      this.init();
    },
    view(row) {
      console.log(row);
      let params = {
        code: row.code,
        // matterType: row.matterType
      };
      queryCommerDeedTaxDetailInfo(params).then((res) => {
        // console.log(res)
        // let arr = []
        // res.data.pictures.forEach((item) => {
        //   let params = {
        //     file: item.picture,
        //     day: 1
        //   }
        //   arr.push(getTempUrl(params))
        // })
        // Promise.all(arr).then(res1 => {
        //   let arr1 = []
        //   arr1 = res1.map((item, index) => ({ picture: item.data, pictureType: res.data.pictures[index].pictureType }))
        this.viewDetail = res.data;
        if (localStorage.getItem("userName") == "admin") {
          this.viewDetail.name = setName(this.viewDetail.name);
          this.viewDetail.phone = setTel(this.viewDetail.phone);
          this.viewDetail.idCard = setCertNo(this.viewDetail.idCard);
        }
        this.viewDetail.idCardPicture = res.data.pictures.filter(
          (item) => item.pictureType === 1
        );
        this.viewDetail.bankCardPicture = res.data.pictures.filter(
          (item) => item.pictureType === 5
        );
        this.viewDetail.contract = res.data.pictures.filter(
          (item) => item.pictureType === 2
        );
        this.viewDetail.certificate = res.data.pictures.filter(
          (item) => item.pictureType === 3
        );
        this.viewDetail.voucher = res.data.pictures.filter(
          (item) => item.pictureType === 4 || item.pictureType === 6
        );
        this.viewShow = true;
        // })
        let reason = [];
        res.data.recordVos.map((item) => {
          if (item) {
            reason.push(item);
          }
        });
        this.recordList = reason.map((item) => {
          item.stateName = this.getSatusArr1(item.state)
            ? this.getSatusArr1(item.state).stateName
            : "未知状态";
          return item;
        });
        this.examineList = this.recordList;
        this.examineList.forEach((item) => {
          item.state != 4 && item.state != 9
            ? (item.state = "通过")
            : (item.state = "拒绝");
        });
        this.totalList = this.examineList;
        console.log(this.totalList);
        this.viewShow = true;
      });
    },
    record(row) {
      console.log(1);
      // console.log(row);

      queryCommerDeedTaxRecord({ code: row.code }).then((res) => {
        console.log(res.data);
        let reason = [];
        res.data.map((item) => {
          if (item) {
            reason.push(item);
          }
        });
        console.log(reason);
        this.recordList = reason.map((item) => {
          item.stateName = this.getSatusArr1(item.state)
            ? this.getSatusArr1(item.state).stateName
            : "未知状态";
          return item;
        });
        this.recordShow = true;
      });
    },
    getSatusArr1(state) {
      return this.stateList1.filter((item) => {
        return item.state == state;
      })[0];
    },
    pass(row) {
      console.log(row);
      this.rowDetail = row;
      this.$prompt(`确定通过该申请的初审吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入原因",
        inputType: "textarea",
        type: "warning",
      })
        .then(({ value }) => {
          if (!value) {
            this.$message.error("未输入原因");
            return;
          }
          queryCommerDeedTaxDetailInfo({ code: row.code }).then((res) => {
            if (res.success) {
              let params = {
                code: row.code,
                idCard: res.data.idCard,
                phone: res.data.phone,
                createTime: row.createTime,
                checkArea: row.checkArea,
                name: this.userName,
                departmentName: this.departmentName,
                state: 8,
                reviewerId: row.reviewerId,
                reason: value,
              };
              updateCommerInitDepartmentState(params).then((res) => {
                if (res.success) {
                  this.$message.success(`初审通过`);
                  this.init();
                  // 查询详情
                  // 判断是否完成初审，进行模板填充及下载
                  let params = {
                    code: row.code,
                    // matterType: row.matterType
                  };
                  Promise.all([
                    queryCommerDeedTaxDetailInfo(params),
                    queryCommerDeedTaxRecord(params),
                  ]).then((res) => {
                    if (res[0].data.state == 1) {
                      this.detail = res[0].data;
                      this.arrList = res[1].data;
                      this.detail.recordVos.forEach((item) => {
                        item.departmentName.search("财政") != -1
                          ? (this.arr1 = item.reason)
                          : "";
                        item.departmentName.search("不动产") != -1
                          ? (this.arr2 = item.reason)
                          : "";
                        item.departmentName.search("税务") != -1
                          ? (this.arr3 = item.reason)
                          : "";
                      });
                      this.initTemplate();
                    }
                  });
                } else {
                  this.$message.warning(
                    res.msg || "该申请已被其他部门驳回，无法审核通过"
                  );
                }
              });
            }
          });
        })
        .catch(() => {
          // console.log("取消审核");
        });
    },
    initTemplate() {
      let that = this;

      let promiseText = that.$store.state.utils.promiseText;
      let text = "";
      if (
        that.realEstateArea == "丹阳市" &&
        that.detail.commitmentType == "1"
      ) {
        // 单独所有、共同共有
        text = promiseText.alone;
      } else if (
        that.realEstateArea == "丹阳市" &&
        that.detail.commitmentType == "2"
      ) {
        // 按份共有

        text = promiseText.together;
      } else {
        text = promiseText.default;
      }
      let arr = {};
      arr.promiseText = text;

      arr.time = that.detail.createTime.split(" ")[0];
      arr.commitmentTypeName =
        that.detail.commitmentType == 1 ? "单独所有、共同共有" : "按份共有";
      arr.name = that.detail.name;
      arr.idCard = that.detail.idCard;
      arr.title = "商办用房";
      arr.birthDate =
        that.detail.idCard.substring(6, 10) +
        "-" +
        that.detail.idCard.substring(10, 12) +
        "-" +
        that.detail.idCard.substring(12, 14);
      arr.address = that.detail.address;
      arr.phone = that.detail.phone;
      arr.realEstateAddress = that.detail.realEstateAddress;
      arr.realEstateCard = that.detail.realEstateCard;
      arr.square = that.detail.square;
      arr.bank = that.detail.bank;
      arr.bankCard = that.detail.bankCard;
      arr.arr1 = that.arr1 || ""; // 财政
      arr.arr2 = that.arr2 || ""; // 不动产
      arr.arr3 = that.arr3 || ""; // 税务
      if (this.$route.query.realEstateArea != "句容市") {
        arr.arr1 = that.arr1 || ""; // 财政
        arr.arr2 = that.arr2 || ""; // 不动产
        arr.arr3 = that.arr3 || ""; // 税务
        this.docxsrc = "./static/deedTax1.docx"; //模板文件的位置
      } else {
        arr.arr3 = that.arr3 || ""; // 税务
        this.docxsrc = "./static/deedTax2.docx"; //模板文件的位置
      }
      // let docxname = '购房契税补贴申请表'; //导出文件的名字
      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent(this.docxsrc, function (error, content) {
        // docxsrc是模板。我们在导出的时候，会根据此模板来导出对应的数据
        // 抛出异常
        // debugger
        if (error) {
          throw error;
        }
        // 创建一个PizZip实例，内容为模板的内容
        let zip = new PizZip(content);
        // 创建并加载docx templater实例对象
        let doc = new docxtemplater().loadZip(zip);
        // 设置模板变量的值
        // console.log("arr666---", arr);
        doc.setData({
          ...arr, // e中的数据可以再模板中直接使用
        });
        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          };
          console.log(
            JSON.stringify({
              error: e,
            })
          );
          throw error;
        }
        // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
        let out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        console.log("out----", out);
        uploadWordFile(
          new File([out], "deed-text" + new Date().valueOf() + ".docx", {
            type: out.type,
          })
        ).then((res) => {
          console.log("文件的res----", res);
          if (res.success) {
            let params = {
              code: that.detail.code,
              fileUrl: res.data,
            };
            saveCommerFileUrl(params).then((res) => {
              console.log("初审通过后的传填充文件给后端---", res);
            });
          } else {
            that.$message.error(res.msg);
            queryCommerDeedTaxDetailInfo({ code: that.rowDetail.code }).then(
              (res) => {
                console.log(res);
                if (res.success) {
                  let params = {
                    code: that.rowDetail.code,
                    phone: res.data.phone,
                    reviewerId: that.rowDetail.reviewerId,
                    state: res.data.state,
                  };
                  initCommerDepartmentRevocation(params).then((res) => {
                    console.log(res);
                    that.init();
                  });
                }
              }
            );
          }
        });
        // 将目标文件对象保存为目标类型的文件，并命名
        // saveAs(out, docxname);
      });
    },
    deny(row) {
      this.$prompt(`确定驳回该申请的初审吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入原因",
        inputType: "textarea",
      })
        .then(({ value }) => {
          if (!value) {
            this.$message.error("未输入原因");
            return;
          }
          queryCommerDeedTaxDetailInfo({ code: row.code }).then((res) => {
            console.log(res);
            if (res.success) {
              let params = {
                code: row.code,
                idCard: row.idCard,
                phone: res.data.phone,
                createTime: row.createTime,
                checkArea: row.checkArea,
                name: this.userName,
                departmentName: this.departmentName,
                state: 9,
                reviewerId: row.reviewerId,
                reason: value,
              };

              updateCommerInitDepartmentState(params).then((res) => {
                console.log("res-", res);

                this.$message.success(`初审驳回成功`);
                this.init();
              });
            }
          });
        })
        .catch(() => {
          // console.log("取消审核");
        });
    },
    drevokeeny(row) {
      console.log(row);
      this.$confirm(`确定撤回该申请的初审吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        queryCommerDeedTaxDetailInfo({ code: row.code }).then((res) => {
          console.log(res);
          if (res.success) {
            let params = {
              code: row.code,
              phone: res.data.phone,
              reviewerId: row.reviewerId,
              state: res.data.state,
            };
            initCommerDepartmentRevocation(params).then((res) => {
              console.log(res);
              if (res.success || res.code == 200) {
                this.$message.success(res.data || "审核撤回成功");
                this.init();
              } else {
                this.$message.error(res.msg);
                this.init();
              }
            });
          }
        });
      });
    },
    reassignment(row) {
      this.params.code = row.code;
      this.params.checkArea = row.checkArea;
      this.reassignmentShow = true;
    },
    closeDialog() {
      this.reassignmentShow = false;
      this.params = {
        code: "",
        checkArea: "",
        departmentCode: "10000031",
      };
    },
    handleChange(value) {
      console.log(value);
      if (value.length == 2) {
        this.params.checkArea = value[1];
      } else {
        this.params.checkArea = value[0];
      }
    },
    determine() {
      this.$confirm(`确定改派该申请的审核部门吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(this.params);
        updateCommerCheckArea(this.params).then((res) => {
          console.log(res);
          if (res.success) {
            this.reassignmentShow = false;
            this.$message.success(`改派成功`);
            this.init();
          } else {
            this.$message.warning(
              res.msg || "该申请已被其他部门驳回，无法审核通过"
            );
          }
        });
      });
    },
    closedownLoad() {
      (this.downLoadShow = false), (this.downLoadParams.state = "");
      this.downLoadParams.begTime = "";
      this.downLoadParams.endTime = "";
      this.date = "";
    },
    time(value) {
      this.downLoadParams.begTime = value && value.length == 2 ? value[0] : "";
      this.downLoadParams.endTime = value && value.length == 2 ? value[1] : "";
    },
    downLoad() {
      console.log(this.downLoadParams);
      if (!this.downLoadParams.state) {
        this.$message.error(`请选择状态`);
        return;
      } else if (this.downLoadParams.state === "null") {
        this.downLoadParams.state = null;
      }
      if (
        !this.downLoadParams.begTime ||
        !this.downLoadParams.endTime ||
        this.date == ""
      ) {
        this.$message.error(`请选择日期`);
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
      });
      userCommerExport(this.downLoadParams)
        .then((res) => {
          let a =
            new Date().getFullYear() +
            "-" +
            (new Date().getMonth() + 1 < 10
              ? "0" + (new Date().getMonth() + 1)
              : new Date().getMonth() + 1) +
            "-" +
            (new Date().getDate() < 10
              ? "0" + new Date().getDate()
              : new Date().getDate());
          downFile(`契税补贴-${a}.xls`, new Blob([res.data]));
          this.downLoadShow = false;
          this.downLoadParams.state = "";
          this.date = "";
        })
        .finally(() => loading.close());
    },
  },
  created() {
    this.userName = localStorage.getItem("userName");
    // 10000031  财政局code   10000032 税务局code    10000033  不动产登记中心code
    this.searchForm.departmentCode = this.$route.query.departmentCode;
    this.realEstateArea = this.$route.query.realEstateArea
      ? this.$route.query.realEstateArea
      : null;
    // departmentName: 审核部门名称（左侧列表）
    this.departmentName = this.$route.query.departmentName;
    this.init();
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/stylus/common';

.content {
  max-height: 60vh;
  overflow-y: auto;

  .cell {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #eee;

    .label {
      width: 150px;
      color: #999;
      text-align: left;

      span {
        color: red;
        font-size: 12px;
      }
    }

    .value {
      color: #000;
      text-align: left;
    }

    .value1 {
      color: red;
    }

    .value2 {
      color: green;
    }

    .info {
      .item {
        width: 100%;
        text-align: left;
        color: #000;
        margin-bottom: 10px;
      }

      .item:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
