<template>
  <div>
    <el-drawer
      size="60%"
      :title="title + '列表'"
      :visible.sync="drawer"
      direction="btt"
      :append-to-body="true"
      :modal-append-to-body="true"
      @close="close"
      class="drawer-box"
    >
      <el-form
        :model="searchForm"
        ref="form"
        class="search-box"
      >
        <el-form-item label="" prop="shapeName" class="form-item">
          <el-input 
           v-model.trim="searchForm.shapeName" 
           placeholder="区域名称"
           clearable
           @keydown.enter.native="filterData"
           @clear="filterData"
          />
        </el-form-item>
        <el-form-item label="" prop="createBy" class="form-item">
          <el-input 
           v-model.trim="searchForm.createBy" 
           placeholder="创建者柜员号"
           clearable
           @keydown.enter.native="filterData"
           @clear="filterData"
          />
        </el-form-item>
        <el-form-item label="" prop="auditStatus" class="form-item">
          <el-select 
           v-model="searchForm.auditStatus" 
           placeholder="审批状态"
           clearable
           @clear="filterData" 
           @change="filterData"
          >
            <el-option 
              v-for="item in statusList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="opsDept" class="form-item">
          <el-select 
           v-model="searchForm.opsDept" 
           placeholder="业务部门归属"
           clearable
           @clear="filterData" 
           @change="filterData"
          >
            <el-option 
              v-for="item in businessBelongList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
            <el-button 
              type="primary" 
              size="small" 
              @click="filterData"
            >
              查询
            </el-button>
            <el-button 
              size="small" 
              type="plain" 
              @click="resetData"
            >
              重置
            </el-button>
        </el-form-item>
      </el-form>
      <common-table
        v-loading="pageLoading"
        :table-data="tableData"
        :table-coloumns="tableColoumns"
        :page-size="pageSize" 
        :pagination="true" 
        :total-rows="total" 
        :current-page="pageNum"
        @onPageChange="handleCurrentChange"
        :layout="layout"
        maxHeight="310"
      >
        <template #layerName>
          <span>{{ title }}</span>
        </template>
        <template #operate="scope">
          <el-button
            type="text"
            size="small"
            class="create-btn"
            @click="onDetail(scope.row)"
          >
            地图
          </el-button>
          <el-button
            type="text"
            size="small"
            class="create-btn"
            :disabled="scope.row.batchFlag || scope.row.deptId != deptId"
            @click="onEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            class="create-btn"
            :disabled="scope.row.batchFlag"
            @click="onPreviewCustomer(scope.row)"
          >
            查看客户
          </el-button>
          <el-button
            type="text"
            size="small"
            class="create-btn"
            @click="approveAgain(scope.row)"
            v-if="scope.row.deptId == deptId && scope.row.auditStatus == '2'"
          >
            重新申请
          </el-button>
          <!--  -->
          <el-button
            type="text"
            size="small"
            class="create-btn"
            @click="approveData(scope.row)"
            v-if="(currentRole == scope.row.opsDept) && scope.row.auditStatus == '0'"
          >
            审批
          </el-button>
        </template>
      </common-table>
    </el-drawer>
    <customer-modal
      ref="customerModal"
      cardType="featured"
      :detailInfo="detailInfo"
      :btnType='2'
    ></customer-modal>
    <!-- 审批 -->
      <el-drawer
            title=""
            :visible.sync="showApprove"
            :size="550"
            :with-header="false"
            direction="rtl"
            :append-to-body="true"
            :wrapperClosable="false"
            >
            <div class="follow-main">
                <div class="collapse" @click="cancelApprove">
                    <span>收起>></span>
                </div>
                <div class="common-title">审批流程</div>
                <div class="block">
                    <el-timeline>
                      <el-timeline-item color="#0bbd87">
                          <div class="name">申请人：{{approveInfo.updateByName}}</div>
                          <div class="status">
                            状态：<span>已提交</span>申请时间：<span>2024-03-12 14:45:12</span>
                          </div>
                      </el-timeline-item>
                      <el-timeline-item color="#4886f8">
                          <div class="name">审批人：总行{{approveInfo.opsDeptName}}管理员</div>
                          <div class="status">
                            状态：<span>审批中</span>
                          </div>
                      </el-timeline-item>
                    </el-timeline>
                </div>
                <el-form :model="formApprove" :rules="formApproveRules" ref="formApprove" class="my-form">
                  <span class="btbz">*</span>
                    <el-form-item label="审批意见" prop="auditRemark">
                        <el-input 
                            style="width: 300px" 
                            type="textarea" 
                            placeholder="请输入" 
                            v-model="formApprove.auditRemark" 
                            :maxlength="200" 
                            :show-word-limit="true" 
                        ></el-input>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmitPass">通过</el-button>
                    <el-button type="danger" @click="onSubmitReject" class="handle-btn">拒绝</el-button>
                </div>
            </div>
      </el-drawer>
  </div>
</template>
<script>
import CommonTable from "@/components/Common/common-table";
import CustomerModal from "../customer-modal.vue";
import { businessBelongList } from '../../../create/utils';
import { checkEdit,approveApi,approveAgainApi,lookAreasMap } from "@/api/grid/draw-area";
import { Message } from 'element-ui';
import { mapGetters } from 'vuex'
export default {
  name: "MenulistModal",
  props: ["drawer","layerId"],
  components: {
    CommonTable,
    CustomerModal,
  },
  data() {
    return {
      layout:"total, prev,pager, next",
      businessBelongList: businessBelongList,
      pageLoading: false,
      detailInfo: {},
      tableColoumns: [
        {
          prop: "createBy",
          label: "创建者",
          align: "left",
        },
        // {
        //   prop: "layerName",
        //   label: "区域类型",
        //   align: "left",
        //   type: "slot",
        //   slotType: "layerName",
        // },
        {
          prop: "shapeId",
          label: "区域编号",
          align: "left",
        },
        {
          prop: "shapeName",
          label: "区域名称",
          align: "left",
        },
        {
          prop: "areades",
          label: "区域规模",
          align: "left",
        },
        {
          prop: "opsDeptName",
          label: "业务部门归属",
          align: "left",
        },
        {
          prop: "remark",
          label: "区域备注",
          align: "left",
        },
        {
          prop: "auditStatusName",
          label: "审批状态",
          align: "left",
        },
        {
          prop: "auditRemark",
          label: "审批意见",
          align: "left",
        },
        {
          prop: "operate",
          label: "操作",
          slotType: "operate",
          width: "250px",
          type: "slot",
        },
      ],
      pageInfo: {
        pageSize: 5,
        pageNum: 1,
        total: 0,
      },
      searchForm: {
        shapeName: '',
        opsDept: '',
        createBy: '',
        auditStatus:"",
      },
      tableData: [],
      statusList:[
        {label:'审批中',key:'0'},
        {label:'通过',key:'1'},
        {label:'拒绝',key:'2'},
      ],
      showApprove:false,
      formApprove:{
        auditRemark:''
      },
      formApproveRules:{
        // remark: [
        //     { 
        //         required: true, 
        //         message: '请输入',
        //         trigger: 'blur',
        //     },
        // ]
      },
      currentRole:'',
      approveInfo:{},
      pageSize: 10,
      pageNum: 1,
      total: 0,
    };
  },
  watch: {
    ["$store.state.featuredAreas.shapeList"](newVal) {
      this.tableData = newVal[0]?.children ?? [];
    }
  },
  computed: {
    ...mapGetters(["roles",'userName','deptId']),
    //对公
    isPublic() {
      return this.roles.includes("headPublic")
    },
    //对私
    isPrivate() {
      return this.roles.includes("headPrivate")
    },
   //运管部
    isHeadOps() {
      return this.roles.includes("headOps") 
    },
   //总行
    isHeadAdmin() {
      return this.roles.includes("headAdmin") 
    },
    title() {
      const { shapeList } = this.$store.state.featuredAreas;
      return shapeList[0]?.layerName;
    },
  },
  mounted() {
    this.currentRole = this.isPrivate?'0':this.isPublic?'1':this.isHeadOps?'2':'';
    this.getList();
  },
  methods: {
    // 收起
    cancelApprove(){
      this.formApprove.auditRemark = '';
      this.showApprove = false;
    },
    // 审批
    handleApprove(type){
      approveApi({
        layerId:this.approveInfo.layerId,
        shapeId:this.approveInfo.shapeId,
        auditRemark:this.formApprove.auditRemark,
        auditStatus:type
      }).then(res=>{
        if(res.code == 200){
          Message.success('审批完成');
          this.formApprove.auditRemark = '';
          this.showApprove = false;
          this.getList()
          this.$emit('refreshApprove')
        }
      })
    },
    // 审批通过
    onSubmitPass(){
       if(!this.formApprove.auditRemark){
          Message.warning('请输入审批意见');
          return;
       }
       this.handleApprove('1');
    },
    // 审批拒绝
    onSubmitReject(){
      if(!this.formApprove.auditRemark){
          Message.warning('请输入审批意见');
          return;
       }
       this.handleApprove('2');
    },
    // 审批
    approveData(row){
      console.log(row)
      this.approveInfo=row;
      this.approveInfo.updateByName = row.createBy;
      this.formApprove.auditRemark = row.auditRemark;
      this.showApprove=true;
    },
    // 重新申请
    approveAgain(row){
      approveAgainApi({...row}).then(res=>{
        if(res.code == 200){
          Message.success('重新申请成功');
          this.getList()
          this.$emit('refreshApprove')
        }
      })
    },
    onDetail(row) {
      this.close();
      this.$emit("draw-polygon", [row]);
    },
    onPreviewCustomer(row) {
      this.detailInfo = row;
      this.$refs.customerModal.onOpen();
    },
    /**
     * 判断是否有编辑权限
     */
    async toCheckEdit(shapeId) {
      const res = await checkEdit({ shapeId });
      if (res.code === 200) return false;
      else return true;
    },
    async onEdit(row) {
      // const flag = await this.toCheckEdit(row.shapeId);
      // if (flag) return;
      this.close();
      this.$emit("draw-polygon", [row]);
      this.$emit('set-form', row);
    },
    close() {
      this.$emit("close");
    },
    // filterData(e) {
    //   const { shapeName = '', createBy = '', opsDept = '' } = this.searchForm;
    //   const { shapeList } = this.$store.state.featuredAreas;
    //   const data = shapeList[0]?.children ?? [];
    //   this.pageLoading = true;
    //   if (shapeName || createBy || opsDept) {
    //     let newData = [...data];
    //     if (shapeName) {
    //       newData = newData.filter(item => {
    //         return item.shapeName.indexOf(shapeName) >= 0;
    //       });
    //     }
    //     if (createBy) {
    //       newData = newData.filter(item => {
    //         return item.createBy.indexOf(createBy) >= 0;
    //       });
    //     }
    //     if (opsDept) {
    //       newData = newData.filter(item => {
    //         return item.opsDept === opsDept;
    //       });
    //     }
    //     this.tableData = newData;
    //   } else {
    //     this.tableData = data;
    //   }
    //   this.pageLoading = false;
    // },
    // resetData() {
    //   this.searchForm={};
    //   this.pageLoading = true;
    //   const { shapeList } = this.$store.state.featuredAreas;
    //   const data = shapeList[0]?.children ?? [];
    //   this.tableData = data;
    //   this.pageLoading = false;
    // },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getList()
    },
    getList(){
      this.pageLoading = true;
      lookAreasMap({
        ...this.searchForm,
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        layerId:this.layerId,
      }).then(res=>{
        if(res.code == 200){
          const newData = res.rows.map((item) => {
              const index = this.businessBelongList.findIndex(i => i.key === item.opsDept)
              return {
                ...item,
                id: item.shapeId,
                label: item.shapeName,
                // color: params.color,
                layerId: item.layerId,
                layerName: item.layerName,
                areades: `${ item?.businessCount || 0}企业, ${ item?.merchantCount || 0}商户, ${item?.retailCount || 0}个人`,
                opsDeptName: index > -1 ? this.businessBelongList[index].label : '',
                auditStatusName:item.auditStatus == '0'?'审批中':
                                item.auditStatus == '1'?'通过':
                                item.auditStatus == '2'?'拒绝':''
              };
            });
            this.tableData = newData;
            this.total = res.total;
        }
        this.pageLoading = false;
      })
    },
    filterData(){
      this.pageNum=1;
      this.getList()
    },
    resetData(){
      this.searchForm={};
      this.pageNum=1;
      this.getList()
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";
.drawer-box {
  ::v-deep .el-drawer__container {
    position: absolute;
    width: calc(100% - #{$base-sidebar-width});
    left: auto;
  }
  ::v-deep .el-drawer__body {
    padding: 0 20px 20px;
  }
  ::v-deep .el-drawer__header {
    font-size: 20px;
    color: #000;
    font-weight: bold;
  }
}

.hideSidebar .drawer-box {
  ::v-deep .el-drawer__container {
    width: calc(100% - 54px);
  }
}

.search-box{
  // width: 300px;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  .form-item{
    margin-right: 10px;
  }
  .el-icon-search{
    font-size: 18px;
    color: #4886f8;
    margin-right: 6px;
    margin-top: 4px;
  }
}
.follow-main{
    padding: 10px 47px;
    .title{
        font-weight: bold;
    }
    .common-title{
        position: relative;
        color: #222222;
        line-height: 35px;
        font-weight: 600;
        font-size: 16px;
        padding-left: 10px;
        margin: 0;
        margin-bottom: 10px;
        &::before {
            position: absolute;
            top: 50%;
            transform: translatey(-50%);
            left: 0;
            content: '';
            width: 3px;
            background-color: #4886f8;
            height: 16px;
            border-radius: 2px;
        }
        //  margin-left: -6px;
    }
    .dialog-footer{
        text-align: center;
    }
    ::v-deep .el-form-item__label{
        min-width: 80px;
    }
    .collapse{
    position: fixed;
    right: 550px;
    background: #fff;
    height: 100px;
    font-size: 14px;
    color: #4886f8;
    margin-left: 2px;
    display: flex;
    align-items: center;
    top: 38%;
    cursor: pointer;
    padding-left: 5px;
    border-radius: 10px 0 0 10px;
  }
  .block{
    .name{
      font-size: 14px;
      color: #606266;
    }
    .status{
      color:#b9b9b9;
      font-size: 12px;
      margin-top: 5px;
      padding-left: 2px;
    }
  }
  .my-form{
    display: flex;
  }
  .btbz{
    color: #ff4d42;
    display: inline-block;
    line-height: 40px;
    margin-right: -10px;
  }
  }
</style>