<template>
  <basic-container>

    <el-tabs type="card" v-model="cycle" @tab-click="handleClick">
      <el-tab-pane label="每日報表" name="day">
      </el-tab-pane>
      <el-tab-pane label="每週報表" name="week">
      </el-tab-pane>
      <el-tab-pane label="每月報表" name="month">
      </el-tab-pane>
    </el-tabs>

    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :before-close="beforeClose"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.checklist_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.checklist_download"
                   @click="handleDownload">下載
        </el-button>
      </template>

      <template slot="menu" slot-scope="{row, index}">
        <!--        <el-button size="small" class="el-button&#45;&#45;text" v-if="permission.checklist_delete " @click="$refs.crud.rowDel(row, index)"><i class="el-icon-delete"></i> 刪 除</el-button>-->
        <el-button size="small" class="el-button--text" v-if="permission.checklist_view" @click="$refs.crud.rowView(row, index)"><i class="el-icon-view"></i> 查 看</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.checklist_edit && userInfo.user_id == row.createUser" @click="$refs.crud.rowEdit(row, index)"><i class="el-icon-edit"></i> 編 輯</el-button>
      </template>

      <template slot="isChecked" slot-scope="{row, index}">
        <!--        <el-tag size="small " type="primary" plain v-if="row.isChecked == 1">√</el-tag>-->
        <el-tag size="small " type="success" plain v-if="row.isChecked">已核對</el-tag>
        <el-tag size="small " type="danger" plain v-if="!row.isChecked">未核對</el-tag>
      </template>

      <template slot="isCheckedForm" slot-scope="{row, index}">
        <el-checkbox v-model="row.isChecked"></el-checkbox>
        <el-tag size="small " type="success" plain v-if="row.isChecked">已核對</el-tag>
        <el-tag size="small " type="danger" plain v-if="!row.isChecked">未核對</el-tag>
      </template>

      <template slot="titleForm" slot-scope="{row, index}">
        <div v-html="title" style="white-space: pre-line;color: red;font-weight: bold;"></div>
      </template>
      <template slot="titleLabel" slot-scope="{row, index}">
        <span style="color: red;font-weight: bold;">注意事項：</span>
      </template>

    </avue-crud>

  </basic-container>
</template>

<script>
  import {getList, getDownloadList, add, update, remove} from "@/api/bank/checklist";
  import {mapGetters} from "vuex";
  import { getCurrentDept } from "@/api/system/dept";
  import {dateFormat} from "../../util/date";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import {getDictionary} from "../../api/system/dict";

  export default {
    name: "init-checklist",
    data() {
      return {
        isManageUser: false,

        titleDay: '',
        titleWeek: '',
        titleMonth: '',

        title: "",
        type: "",
        cycle: "day",
        dayType: [],
        dayItem: [],
        dayContent: [],
        weekType: [],
        weekItem: [],
        weekContent: [],
        monthType: [],
        monthItem: [],
        monthContent: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          addTitle: '新增【每日核對記錄表】',
          editTitle: '編輯【每日核對記錄表】',
          viewTitle: '查看【每日核對記錄表】',
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          editBtn: false,
          delBtn: false,
          viewBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: '注意事項',
              prop: 'title',
              formslot: true,
              hide: true,
              type: 'text',
              span: 24
            },
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              disabled: true,
              display: false,
              search: false,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              disabled: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              disabled: true,
              span: 24,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "區域/支行",
              prop: "orgNos",
              hide: true,
              display: false,
              searchMultiple: true,
              search: true,
              type: "tree",
              dicData: [],
              props: {
                label: "title",
                value: "key"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "核對日期",
              prop: "checkDateRange",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              searchRange:true,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              search: true,
              rules: [{
                required: true,
                message: "請輸入交接日期",
                trigger: "blur"
              }]
            },
            {
              label: "分類",
              prop: "type",
              type: "select",
              // cascaderItem: ['item'],
              search: true,
              // searchSpan: 4,
              searchMultiple: true,
              // dicUrl: "/api/blade-system/dict/dictionary?code=check_category",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              /*focus: ({value, column}) => {
                let $type = this.findObject(this.option.column, 'type');
                let dicData = this.dayType;
                $type.dicData = [];
                debugger
                /!*dicData.forEach(item => {
                  item.disabled = ["edit", "add"].includes(this.type) && item.isSealed == 1;
                })*!/
                $type.dicData = dicData;
              },*/
              change: ({value}) => {
                console.log("change-" + this.type)
                if (!value || value.length == 0) return;
                // 有值，打開核對項目下拉選
                this.findObject(this.option.column, "item").disabled = false;
                let arr = [];
                let itemArr = [];
                if (this.cycle == "day"){
                  itemArr = this.dayItem;
                }
                if (this.cycle == "week"){
                  itemArr = this.weekItem;
                }
                if (this.cycle == "month"){
                  itemArr = this.monthItem;
                }

                for (let i = 0; i < itemArr.length; i++) {
                  let item = itemArr[i];
                  if (item.dictKey.indexOf(value) != -1){
                    arr.push(item)
                  }
                }
                this.findObject(this.option.column, 'item').dicData = arr;
                //
                if (this.form.type != value){
                  delete this.form.item;
                }
              },
              rules: [{
                required: true,
                message: "請輸入分類",
                trigger: "blur"
              }]
            },
            {
              label: "核對項目",
              prop: "itemShow",
              type: "select",
              disabled: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=check_item",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              display: false,
            },
            {
              label: "核對項目",
              prop: "item",
              // cascaderItem: ['content'],
              type: "select",
              hide: true,
              search: true,
              // searchSpan: 4,
              searchMultiple: true,
              dicData: [],
              // dicUrl: "/api/blade-system/dict/dictionary?code=check_item",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              focus: ({value, column}) => {
                let $item = this.findObject(this.option.column, 'item');
                let dicData = $item.dicData;
                $item.dicData = [];
                dicData.forEach(item => {
                  item.disabled = ["edit", "add"].includes(this.type) && item.isSealed == 1;
                })
                $item.dicData = dicData;
              },
              rules: [{
                required: true,
                message: "請輸入核對項目",
                trigger: "blur"
              }]
            },
            /* {
              label: "核對內容/標準",
              prop: "content",
              type: "select",
              // dicUrl: "/api/blade-system/dict/dictionary?code=check_content_normal",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              dicFormatter: (res) => {
                let result = [];
                let data = res.data;
                let cycle = this.cycle;
                for (let i = 0; i < data.length; i++) {
                  let item = data[i];
                  if (item.dictKey.indexOf(cycle) != -1){
                    result.push(item)
                  }
                }
                return result;
              },
              rules: [{
                required: true,
                message: "請輸入核對內容/標準",
                trigger: "blur"
              }]
            },
           {
              label: "已核對",
              prop: "isChecked",
              formslot: true,
              rules: [{
                required: false,
                message: "請勾選已核對",
                trigger: "blur"
              }]
            },*/
            {
              label: "核對日期",
              prop: "checkDate",
              type: "datetime",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入核對日期",
                trigger: "blur"
              }]
            },
            {
              label: "核對人",
              prop: "checkName",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入核對人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "核對人員工號",
              prop: "checkNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入核對人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "填報時間",
              prop: "fillingDate",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報時間",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.checklist_add, false),
          viewBtn: this.vaildData(this.permission.checklist_view, false),
          delBtn: this.vaildData(this.permission.checklist_delete, false),
          editBtn: this.vaildData(this.permission.checklist_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      this.initDict();
    },
    mounted() {
      getDeptTree().then(res => {
        const column = this.findObject(this.option.column, "orgNos");
        let treeData = getTree(res.data.data, this.userInfo.dept_id);
        column.dicData = treeData;
      });
      getStandardByCode("checklist_day").then(res => {
        // getStandardByCode("tellertrunk").then(res => {
        const data = res.data.data;
        if (Object.keys(data).length > 0){
          this.titleDay = data.content;
          this.title = data.content;
        }else {
          this.option.column.splice(0,1)
        }
      });
      getStandardByCode("checklist_week").then(res => {
        const data = res.data.data;
        if (Object.keys(data).length > 0) {
          this.titleWeek = data.content;
        }
      });
      getStandardByCode("checklist_month").then(res => {
        const data = res.data.data;
        if (Object.keys(data).length > 0) {
          this.titleMonth = data.content;
        }
      });
    },
    methods: {
      handleDownload(){
        if (this.selectionList.length === 0) {
          let tip = "確定下載篩選的" + this.page.total + "條數據嗎？"
          this.$confirm(tip, {
            confirmButtonText: "確定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              getDownloadList(Object.assign({cycle: this.cycle}, this.query)).then(res => {
                this.downLoadData(res.data.data, true)
              });
            })
        }else{
          this.downLoadData(this.selectionList, false)
        }
      },
      downLoadData(data, isAll){
        let columns = this.deepClone(this.option.column);
        for (let i = 0; i < columns.length; i++) {
          let item = columns[i];
          if (item.hide || item.prop == 'process'){
            columns.splice(i, 1);
            i--;
          }
          if (!isAll && (item.type == 'select' || item.type == 'tree')){
            item.prop = '$' + item.prop;
          }
        }
        let title = '';
        if (this.cycle == "day"){
          title = "每日核對記錄表";
        }
        if (this.cycle == "week"){
          title = "每週核對記錄表";
        }
        if (this.cycle == "month"){
          title = "每月核對記錄表";
        }
        // 针对表格和搜索的字典字段分开的特殊情况处理
        if (isAll){
          this.findObject(columns, "itemShow").prop = "item";
        }
        this.$Export.excel({
          title: title || new Date().getTime(),
          columns: columns,
          data: data
        });
      },
      handleClick(tab, event) {
        if (this.cycle == 'day'){
          this.option.addTitle  = '新增【每日核對記錄表】';
          this.option.editTitle = '編輯【每日核對記錄表】';
          this.option.viewTitle = '查看【每日核對記錄表】';

          this.findObject(this.option.column, 'type').dicData = this.dayType;
          this.findObject(this.option.column, 'item').dicData = this.dayItem;
          this.title = this.titleDay;
        }else if (this.cycle == 'week'){
          this.option.addTitle  = '新增【每週核對記錄表】';
          this.option.editTitle = '編輯【每週核對記錄表】';
          this.option.viewTitle = '查看【每週核對記錄表】';

          this.findObject(this.option.column, 'type').dicData = this.weekType;
          this.findObject(this.option.column, 'item').dicData = this.weekItem;
          this.title = this.titleWeek;
        }else{
          this.option.addTitle  = '新增【每月核對記錄表】';
          this.option.editTitle = '編輯【每月核對記錄表】';
          this.option.viewTitle = '查看【每月核對記錄表】';

          this.findObject(this.option.column, 'type').dicData = this.monthType;
          this.findObject(this.option.column, 'item').dicData = this.monthItem;
          this.title = this.titleMonth;
        }
        this.cycle = tab.name;

        this.onLoad(this.page);
      },
      initDict(){
        getDictionary({code: 'check_category'}).then(res => {
          let data = res.data.data;
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            // item.disabled = item.isSealed == 1;
            if (item.dictKey.indexOf('day') != -1){
              this.dayType.push(item)
            }
            if (item.dictKey.indexOf('week') != -1){
              this.weekType.push(item)
            }
            if (item.dictKey.indexOf('month') != -1){
              this.monthType.push(item)
            }
          }
          this.findObject(this.option.column, 'type').dicData = this.dayType;
        })
        getDictionary({code: 'check_item'}).then(res => {
          let data = res.data.data;
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            // item.disabled = item.isSealed == 1;
            if (item.dictKey.indexOf('day') != -1){
              this.dayItem.push(item)
            }
            if (item.dictKey.indexOf('week') != -1){
              this.weekItem.push(item)
            }
            if (item.dictKey.indexOf('month') != -1){
              this.monthItem.push(item)
            }
          }
          this.findObject(this.option.column, 'item').dicData = this.dayItem;
        })
        /*getDictionary({code: 'check_content_normal'}).then(res => {
          let data = res.data.data;
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item.dictKey.indexOf('day') != -1){
              this.dayContent.push(item)
            }
            if (item.dictKey.indexOf('week') != -1){
              this.weekContent.push(item)
            }
            if (item.dictKey.indexOf('month') != -1){
              this.monthContent.push(item)
            }
          }
          this.findObject(this.option.column, 'content').dicData = this.dayContent;
        })*/
      },
      rowSave(row, done, loading) {
        row.isChecked = !row.isChecked ? 0 : 1;
        row.cycle = this.cycle;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.isChecked = !row.isChecked ? 0 : 1;
        row.cycle = this.cycle;
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeClose(done,type){
        this.type = '123'
        console.log('beforeClose')
        done();
      },
      beforeOpen(done, type) {
        this.type = type;
        console.log("beforeOpen"+this.type)
        this.form.title = '添加'
        this.findObject(this.option.column, "item").disabled = true;
        if (type === 'add'){
          let userInfoStr = localStorage.getItem("saber-userInfo");
          let userInfo = JSON.parse(userInfoStr);

          this.form.checkNo =userInfo.content.user_ehr;
          this.form.checkName =userInfo.content.user_name;
          this.form.number = 1;
          this.form.handoverDate = dateFormat(new Date(), "yyyy-MM-dd hh:mm");
          getCurrentDept().then(res => {
            const data =  res.data.data;
            this.form.bankNo = data.bankNo;
            this.form.orgNo = data.orgNo;
            this.form.orgName = data.deptName;
          });
        }
        if (["edit", "view"].includes(type)) {
          this.form.isChecked = this.form.isChecked == 1;
          /*getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });*/
        }

        if (["edit", "add"].includes(type)) {
          let $type = this.findObject(this.option.column, 'type');
          let dicData = $type.dicData;
          $type.dicData = [];
          dicData.forEach(item => {
            item.disabled = ["edit", "add"].includes(this.type) && item.isSealed == 1;
          })
          $type.dicData = dicData;
        }

        this.form.title = '添加'
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.checkDateRange){
          params.checkDate_begin = params.checkDateRange[0], params.checkDate_end = params.checkDateRange[1];
          params.checkDateRange = null;
        }
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.type){
          params.type = params.type.join();
        }
        if (params.item){
          params.item = params.item.join();
        }

        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.cycle = this.cycle;
        params.createUser = this.userInfo.user_id;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          data.records.forEach(item => {
            item.itemShow  = item.item;
          })
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
