<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               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.autostruct_delete"
                   @click="handleDelete">刪 除
        </el-button>
      </template>

      <template slot="designForm" slot-scope="{row}">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-design"
                   plain
                   @click="designOption = row.columns, designVisible = true">設計
        </el-button>
      </template>

      <template slot="settingForm" slot-scope="{row}">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-design"
                   plain
                   @click="flowSetting = row, settingVisible = true">設置
        </el-button>
      </template>
    </avue-crud>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :fullscreen="true" :visible.sync="designVisible" title="表單設計">
      <div v-if="designVisible">
        <cy-form-design :callback="designCallback" :option="designOption"></cy-form-design>
      </div>
    </el-dialog>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :visible.sync="settingVisible" title="流程設置" width="70%">
      <div v-if="settingVisible">
        <auto-setting @callback="settingCallback" :flow-setting="flowSetting"></auto-setting>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/bank/autostruct";
  import {mapGetters} from "vuex";
  import CyFormDesign from "../../components/common/cy-form-design";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getRoleTree} from "@/api/system/role";
  import website from '@/config/website';
  import {opStr2opObj} from "../../api/bank/autostruct";
  import AutoSetting from "../../components/autostruct/auto-setting";

  export default {
    components: {AutoSetting, CyFormDesign},
    data() {
      return {
        designVisible: false,
        settingVisible: false,
        designOption: {},

        form: {},
        flowSetting: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          reserveSelection:true,
          dialogClickModal: false,
          column: [
            {
              label: "表名",
              prop: "name",
              search: true,
              span: 12,
              rules: [{
                required: true,
                message: "請輸入表名",
                trigger: "blur"
              }]
            },
            {
              label: "表單設計",
              prop: "design",
              span: 12,
              hide: true,
              viewDisplay: false,
              formslot: true,
            },
            {
              label: "流程開關",
              prop: "approveSwitch",
              span: 12,
              type: "switch",
              dicData: [{
                label: '關',
                value: 0
              }, {
                label: '開',
                value: 1
              }],
              hide: true,
              change: ({value}) => {
                let setObj = this.findObject(this.option.column, "setting");
                setObj.display = value == 1;
                this.findObject(this.option.column, "approveSwitch").span = value == 1 ? 6 : 12;
              }
            },
            {
              label: "流程设置",
              prop: "setting",
              span: 6,
              hide: true,
              display: false,
              viewDisplay: false,
              formslot: true,
            },
            {
              label: "填寫部門",
              prop: "deptId",
              type: "tree",
              multiple: true,
              hide: true,
              span: 12,
              dataType: "string",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "請選擇填寫部門",
                trigger: "click"
              }]
            },
            {
              label: "填寫角色",
              prop: "roleId",
              hide: true,
              // search: true,
              multiple: true,
              span: 12,
              type: "tree",
              dataType: "string",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: false,
                message: "請選擇填寫角色",
                trigger: "click"
              }]
            },
            {
              label: "管理員角色",
              prop: "manageRoleId",
              hide: true,
              // search: true,
              multiple: true,
              span: 24,
              type: "tree",
              dataType: "string",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "請選擇填寫角色",
                trigger: "click"
              }]
            },
            {
              label: "列結構",
              prop: "columns",
              hide: true,
              disabled: true,
              type: "textarea",
              span: 24,
              rules: [{
                required: true,
                message: "請輸入列結構",
                trigger: "blur"
              }]
            },
            {
              label: "創建時間",
              prop: "createTime",
              type: "datetime",
              display: false,
              rules: [{
                required: true,
                message: "請輸入列結構",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission", "userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.autostruct_add, false),
          viewBtn: this.vaildData(this.permission.autostruct_view, false),
          delBtn: this.vaildData(this.permission.autostruct_delete, false),
          editBtn: this.vaildData(this.permission.autostruct_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      getDeptTree().then(res => {
        const column = this.findObject(this.option.column, "deptId");
        let treeData = getTree(res.data.data, this.userInfo.dept_id);
        column.dicData = treeData;
      });
      getRoleTree(website.tenantId).then(res => {
        const column = this.findObject(this.option.column, "roleId");
        column.dicData = res.data.data;
        this.findObject(this.option.column, "manageRoleId").dicData = res.data.data;
      });
    },
    methods: {
      settingCallback(value){
        this.settingVisible = false;
        this.form.approveType = value.approveType;
        this.form.settingType = value.settingType;
        this.form.setting = value.setting;
        this.form.num = value.num;
      },
      designCallback(value){
        this.designVisible = false;
        this.form.columns = value;
      },
      rowSave(row, done, loading) {
        if (row.approveType == 1 && row.settingType == 2){
          // 串行-逐級設置
          delete row.setting;
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (row.approveType == 1 && row.settingType == 2){
          // 串行-逐級設置
          delete row.setting;
        }
        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();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        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;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
