<template>
  <div>
    <div class="cardOne">
      <header-box :headerForm="search" @searchClick="getData" :showButtons="showButtons" @openDialog="openDialog"
        @deleteClick="deleteClick">
      </header-box>
    </div>
    <div class="cardTwo">
      <content-box :loading="loading" @openDialog="openDialog" @deleteClick="deleteClick" :showButtons="showButtons"
        :tableData="tableData" :pagination="pagination" :selectList="multipleSelection"
        @handleSelectionChange="handleSelectionChange" @refreshTable="getData" @showFile="handleClickFile" />
    </div>
    <el-dialog v-dialogDrag :title="title" :visible.sync="isDialogVisible" :close-on-click-modal="false" width="45%">
      <el-form ref="formDataRef" :model="formData" label-width="100px" :rules="formDataRules">
        <el-form-item label="姓名：" prop="fondscode">
          <el-input clearable size="small" v-model.trim="formData.userName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生年月：" prop="time">
          <el-date-picker v-model="formData.time" value-format="yyyy-MM-dd" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号：" prop="idCard">
          <el-input clearable size="small" v-model.trim="formData.idCard" placeholder="请输入身份证号"></el-input>
        </el-form-item>
        <el-form-item label="档号" prop="archiveNo">
          <el-input clearable size="small" v-model="formData.archiveNo" placeholder="请输入档案档号"></el-input>
        </el-form-item>
        <el-form-item label="题名" prop="maintitle">
          <el-input clearable size="small" v-model="formData.maintitle" placeholder="请输入题名"></el-input>
        </el-form-item>
        <el-form-item label=" ">
          <el-button :loading="btnloading" size="mini" type="primary" @click="subClick"><i
              class="iconfont icon-baocun"></i>保存</el-button>
          <el-button size="mini" @click="cancel()"><i class="iconfont icon-error"></i>取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 报表查看 -->
    <show-report :visible="isShowReport" :pdfUrl="pdfUrl" @cancel="cancel" />
  </div>
</template>
<script>
  import {
    message,
    clearObjValue
  } from "@/utils/common";
  import headerBox from "./components/header";
  import contentBox from "./components/content";
  import ShowReport from "@/components/ShowReport";
  import localStronge from "@/api/localData";
  import {createArchiveProvePdf} from "@/api/archiveProveService.js"
  import {
    mapState
  } from "vuex";
  export default {
    data() {
      return {
        pdfUrl:'',
        isShowReport:false,
        btnloading: false,
        formDataRules: {
          userName: [{
            required: true,message: "请输入姓名",trigger: "blur"}, ],
          sex: [{
            required: true,message: "请选择性别",trigger: "change"}, ],
          time: [{
            required: true,message: "请选择出生年月",trigger: "change"}, ],
          idCard: [
            {required: true,message: '身份证不能为空',trigger: ['blur', 'change']},
            {pattern: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
              message: '请输入正确的身份证',
              trigger: ['blur', 'change']
            },
          ],
          archiveNo: [{
            required: true,message: "请输入档号",trigger: "blur"}, ],
            maintitle: [{
            required: true,message: "请输入题名",trigger: "blur"}, ],
        },
        search: {
          userName: ''
        },
        params: {},
        multipleSelection: [],
        title: "",
        isDialogVisible: false,
        formData: {
          userName:'',
          sex:'男',
          time:'',
          idCard:'',
          archiveNo:'',
          maintitle:'',
          birthDay:'',
          birthMonth:'',
          birthYear:''
        },
      }
    },
    components: {
      headerBox,
      contentBox,
      ShowReport
    },
    computed: {
      ...mapState({
        tableData: (state) => state.archiveProveService.tableData,
        pagination: (state) => state.archiveProveService.pagination,
        showButtons: (state) => state.archiveProveService.showButtons,
      }),
      loading: {
        get() {
          return this.$store.state.editingTopics.loading;
        },
        set(val) {
          this.$store.state.editingTopics.loading = val;
        },
      },
    },
    methods: {
      handleClickFile(row){
        let reportUrl = null;
        const prefix =
        process.env.NODE_ENV === "development"
          ? "http://" +
            localStronge.getServiceip().ip +
            ":" +
            localStronge.getServiceip().host
          : "http://" + window.location.host;
        // 查询地址
        createArchiveProvePdf({id:row.id}).then((res)=>{
          if(res.code == 100){
            this.isShowReport = true;
            reportUrl = res.body.url;
            this.pdfUrl =
            prefix + `/point-strategy/${reportUrl}`;
          }
        })
      },
      getData() {
        this.params = {
          page: this.pagination.pageNum,
          limit: this.pagination.pageSize,
          userName:this.search.userName,
        }
        this.$store.dispatch('archiveProveService/getData', this.params).catch(err => {
          this.loading = false
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      deleteClick(val) {
        this.$alert("是否确认删除该数据？", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: async (action) => {
            if (action === "cancel") {
              return false;
            }
            let res;
            if (!val) {
              
              let arr = [];
              this.multipleSelection.map((item) => {
                arr.push(item.id);
              });
              this.$store.dispatch('archiveProveService/batchDelete', {
                ids: arr.join(",")
              }).then(res => {
                this.getData();
                message('success', '删除成功', 3000)
              })
            } else {
              this.$store.dispatch('archiveProveService/deleteList', {
                id: val.id
              }).then(res => {
                this.getData();
                message('success', '删除成功', 3000)
              })
            }
          },
        });
      },
      openDialog(val) {
        clearObjValue(this.formData)
        if (val) {
          this.title = '编辑'
          this.formData = {
            ...val,
            time:`${val.birthYear}-${val.birthMonth}-${val.birthDay} 00:00:00`
          };
          
          this.isDialogVisible = true
        } else {
          this.title = '新增'
          this.isDialogVisible = true;
          this.formData = {
            ...val,
          }
        }
      },
      // 
      subClick() {
        this.$refs["formDataRef"].validate(async (valid) => {
          if (valid) {
            this.btnloading = true;
            if (this.title === '新增') {
                this.formData.birthDay= this.formData.time.slice(8,10),
                this.formData.birthMonth = this.formData.time.slice(5,7),
                this.formData.birthYear = this.formData.time.slice(0,4),
                this.$store.dispatch('archiveProveService/addList', this.formData).then(res => {
                this.btnloading = false;
                this.isDialogVisible = false;
                message('success', '新增成功', 3000)
                this.getData();
              }).catch(err => {
                this.btnloading = false;
              })
            } else {
                this.formData.birthDay= this.formData.time.slice(8,10),
                this.formData.birthMonth = this.formData.time.slice(5,7),
                this.formData.birthYear = this.formData.time.slice(0,4),
                this.$store.dispatch('archiveProveService/updateList', this.formData).then(res => {
                this.btnloading = false;
                this.isDialogVisible = false;
                message('success', '编辑成功', 3000)
                this.getData();
              }).catch(err => {
                this.btnloading = false;
              })
            }
          } else {
            return false;
          }
        });
      },
      cancel() {
        this.isDialogVisible = false;
        this.isShowReport = false;
      }
    },
    created() {
      let btnData = {
        menuid: this.$getMenuId(sessionStorage.getItem("routerIdList"), this.$route.path),
        roleid: sessionStorage.getItem("roleid")
      }
      this.$store.dispatch("allAdministration/getButtonList", btnData);
      this.getData()
    }
  }

</script>
<style lang="scss" scoped>

</style>
