<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @search-reset="searchReset"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-del="deteleFn"
      >
        <template slot="menuLeft">
          <el-button type="primary" @click="addFn"
            ><i class="el-icon-plus mr5"></i>新 增</el-button
          >
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="editFn(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 0"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="updateTy(scope.row, scope.index)"
            >停用
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 1"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="updateQy(scope.row, scope.index)"
            >启用
          </el-button>
        </template>
        <!-- 区域搜索 -->
        <template slot="areaCodesSearch">
          <el-cascader
            v-model="searchFormAreaCodes"
            :options="treeList"
            :key="cascaderKey"
            collapse-tags
            :props="searchCascaderProps"
            clearable
          ></el-cascader>
        </template>
      </avue-crud>
      <!-- 新增/编辑 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="dialogType === 'add' ? '新增' : '编辑'"
        width="60%"
        @close="handleClose"
        :visible.sync="showAddDialog"
      >
        <el-form
          :model="dialogForm"
          :rules="dialogFormRules"
          ref="dialogForm"
          label-width="150px"
        >
          <el-form-item label="企业名称：" prop="entname">
            <el-input
              v-model="dialogForm.entname"
              placeholder="请输入企业名称"
            />
          </el-form-item>
          <el-form-item label="统一社会信用代码：" prop="entcode">
            <el-input
              v-model="dialogForm.entcode"
              placeholder="请输入统一社会信用代码"
            />
          </el-form-item>
          <el-form-item label="权限限制：" prop="deptPermissions">
            <el-select
              class="w100"
              v-model="dialogForm.deptPermissions"
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in deptPermissionsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域：" prop="areaCodesData">
            <el-cascader
              :key="cascaderKey"
              collapse-tags
              class="w100"
              v-model="dialogForm.areaCodesData"
              :options="treeList"
              :props="cascaderProps"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状态：" prop="enableFlag">
            <el-select
              class="w100"
              v-model="dialogForm.enableFlag"
              placeholder="请选择"
            >
              <el-option
                v-for="item in enableFlagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="财务复核方式：" prop="financialReviewType">
            <el-select
              class="w100"
              v-model="dialogForm.financialReviewType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in financialReviewTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose" icon="el-icon-close">取 消</el-button>
          <el-button
            type="primary"
            :loading="buttonLoading"
            icon="el-icon-check"
            @click="submitFn"
            >保 存</el-button
          >
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  saves
} from "@/api/wmdadrugent";
import { tableOption } from "@/const/crud/wmdadrugent";
import { mapGetters } from "vuex";
import { getDictType } from "@/api/common";
import { getAreaTreeApi } from "@/api/areaTree";
import { filterCodes, extractPaths } from "@/util/treeUtils.js";

export default {
  name: "wmdadrugent",
  data() {
    return {
      subForm: {},
      searchFormAreaCodes: [],
      searchForm: {},
      searchCascaderProps: {
        multiple: true,
        label: "name",
        value: "id"
      },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      buttonLoading: false,
      tableOption: tableOption,
      dialogType: "add",
      showAddDialog: false,
      dialogForm: {
        areaCodesData: [],
        financialReviewType: "AUTO"
      },
      dialogFormRules: {
        entname: [
          { required: true, message: "请输入企业名称", trigger: "blur" }
        ],
        entcode: [
          {
            required: true,
            message: "请输入正确的统一社会信用代码",
            pattern: /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/g,
            trigger: "blur"
          }
        ],
        enableFlag: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        financialReviewType: [
          { required: true, message: "请选择财务复核方式", trigger: "change" }
        ],
        areaCodesData: [
          { required: true, message: "请选择区域", trigger: "change" }
        ]
      },
      treeList: [],
      cascaderProps: {
        multiple: true,
        label: "name",
        value: "id"
      },
      deptPermissionsOptions: [], // 权限限制字典
      financialReviewTypeOptions: [],
      enableFlagOptions: [], // 状态字典
      cascaderKey: 0
    };
  },
  mounted() {
    this.getDict();
    this.getAreaTree();
  },
  computed: {
    ...mapGetters(["permissions"], ["userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmdadrugent_add, false),
        editBtn: this.vaildData(this.permissions.admin_wmdadrugent_edit, false)
      };
    }
  },
  methods: {
    // 获取区域树列表
    async getAreaTree() {
      const res = await getAreaTreeApi();
      this.treeList = res.data.data;
    },
    // 新增
    addFn() {
      this.dialogType = "add";
      this.showAddDialog = true;
    },
    // 编辑
    editFn(row, index) {
      const areaCodes = row.areaCodes;
      const treeList = JSON.parse(JSON.stringify(this.treeList));
      const currTree = filterCodes(areaCodes, treeList);
      if (currTree) {
        const ids = extractPaths(currTree);
        row.areaCodesData = ids;
      }
      this.dialogForm = Object.assign({}, row);
      this.dialogType = "edit";
      this.showAddDialog = true;
    },
    // 提交
    submitFn() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          let params = Object.assign({}, this.dialogForm);
          const flattenedArray = params.areaCodesData.flat();
          const areaCodes = Array.from(new Set(flattenedArray));
          params.areaCodes = areaCodes;
          this.buttonLoading = true;
          if (this.dialogType === "add") {
            saves(params)
              .then(data => {
                this.$message.success("添加成功");
                this.buttonLoading = false;
                this.handleClose();
                this.getList(this.page);
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          } else if (this.dialogType === "edit") {
            putObj(params)
              .then(data => {
                this.$message.success("修改成功");
                this.buttonLoading = false;
                this.handleClose();
                this.getList(this.page);
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      ++this.cascaderKey;
      this.$refs.dialogForm.resetFields();
      this.dialogForm.financialReviewType = "AUTO";
      this.dialogForm = {
        areaCodesData: [],
        financialReviewType: "AUTO"
      };
      this.showAddDialog = false;
    },
    // 获取字典
    getDict() {
      // 获取权限限制字典
      getDictType({ type: "dept_permission_type" }).then(res => {
        this.deptPermissionsOptions = res.data.data;
      });
      // 财务限制字典
      getDictType({ type: "financial_review_type" }).then(res => {
        this.financialReviewTypeOptions = res.data.data;
      });
      getDictType({ type: "cro_statu" }).then(res => {
        this.enableFlagOptions = res.data.data;
      });
    },
    // 获取列表数据
    getList(page, params) {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize
        },
        params,
        this.searchForm
      );
      fetchList(obj)
        .then(response => {
          let answer = response.data.data.records;
          answer.forEach(item => {
            if (item.deptPermissions && item.deptPermissions.length > 1) {
              item.deptPermissions = item.deptPermissions.sort((a, b) => a - b);
            }
          });
          this.tableData = answer;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    deteleFn(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate(row, index, done, loading) {
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    updateTy: function(row, index, done, loading) {
      row.enableFlag = "1";
      putObj(row)
        .then(data => {
          this.$message.success("停用成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    updateQy: function(row, index, done, loading) {
      row.enableFlag = "0";
      putObj(row)
        .then(data => {
          this.$message.success("启用成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    searchReset() {
      ++this.cascaderKey;
      this.searchFormAreaCodes = [];
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    extractLastElements(array) {
      // 创建一个新的空数组来存储结果
      let result = [];
      // 遍历输入的二维数组
      for (let i = 0; i < array.length; i++) {
        // 检查内部数组是否非空
        if (array[i].length > 0) {
          // 将内部数组的最后一个元素添加到结果数组中
          result.push(array[i][array[i].length - 1]);
        }
      }
      // 返回结果数组
      return result;
    },
    searchChange(form, done) {
      this.searchForm = form;
      if (this.searchFormAreaCodes.length) {
        const codes = this.extractLastElements(this.searchFormAreaCodes);
        this.searchForm.areaCodes = codes;
      }
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    }
  }
};
</script>
