<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"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
                <template slot="menuLeft"> 
                    <div style="display:flex;align-items: center;">
                        <div style="width:180px">文件存储类型</div>
                        <el-select v-model="query.fileStorageType" placeholder="请选择文件存储类型"
                          @change="queryChange">
                            <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                        <el-link :underline="false" @click="setAllocation" type="primary"><i class="el-icon-s-tools" size="large" style="line-height: 38px; font-size: 24px;margin-left: 5px;"></i></el-link>
                        
                    </div>
                </template>
                <template slot="menuRight" v-if="query.fileStorageType==''">
                  <div>
                    <el-button type="primary"
                      icon="el-icon-plus"
                      circle
                      @click="toadd"></el-button>
                  </div>
                </template>
                <template slot-scope="{type,size,row,index}" slot="menu" v-if="query.fileStorageType!==''">
                  <el-button :size="size" :type="type" @click="cancel(row,index)" :loading="cancelLoad">取消捕获</el-button>
                </template>
    </avue-crud>
      <!-- 编辑元素表单信息 -->
    <el-dialog
      title="设置分类元素数据"
      :visible.sync="setMetadataTag"
      width="60%" :center='true'
      :modal-append-to-body="false"
    >
      <div > 
        <div style="float:right;margin-bottom:20px">
          <el-select v-model="optionvalue" placeholder="请选择文件存储类型"  @change="changeType">
              <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              >
              </el-option>
           </el-select>
          <!-- <el-button type="primary" @click="allocationSave">保存</el-button> -->
        </div>
        <el-table
          :data="MetadataformDatass"
          :row-key="selRowKey"
          border ref="dialogtable"
          style="width: 100%;">
          <el-table-column
            type="selection"
            reserve-selection
            width="55">
          </el-table-column>
          <el-table-column
            prop="containerName"
            label="元数据项">
          </el-table-column>
          <el-table-column
            prop="captureMode"
            label="捕获方式"
            :formatter="tableFormatter">
          </el-table-column>
          <el-table-column
            prop="mandatoryType"
            label="是否必选"
            :formatter="tableFormatter">
          </el-table-column>
       
        </el-table>
        <div class="text-align-c">
          <el-pagination
          @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="page2.current"
            :page-sizes="[20, 40, 60, 100]"
            :page-size="page2.pageSize"
            layout="total, prev, pager, next,sizes"
            :total="page2.total">
          </el-pagination>
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setMetadataTag = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allocationSave"
          :loading="saveload"
        >确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
  
</template>

<script>
import {getDetail,getMetadataDetail,metadataSubmit,metadataUpdate, metadataRemove,getAllocationDetail,allocation,cancelAllocation} from "@/api/tentative/testcollect";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
    options: [
        {
          value: '',
          label: '元数据表'
        },
        {
          value: 'a',
          label: '普通'
        },
        {
          value: "b",
          label: '竣工图'
        }, {
          value: "c",
          label: '计量'
        }, {
          value: "d",
          label: '质检'
        }, {
          value: "e",
          label: '声像'
        }, {
          value: "f",
          label: '隐蔽'
        }, {
          value: "g",
          label: '试验'
        }, {
          value: "h",
          label: '管理文件'
        }, {
          value: "i",
          label: '变更令'
        }
        ],
     optionvalue: '',
      form: {},
      query: {
        fileStorageType:'',
      },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search:{},
      selectionList: [],
      option: {
         refreshBtn: false,      // 刷新 
        columnBtn: false,       // 操作列显隐
        cellBtn:true,//开启行编辑按钮
        addBtn:false,
        menuWidth:330,
        height:'auto',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 0,
        border: true,
        index:true,
        indexLabel:'序号',
        viewBtn: true,
        selection: false,
        dialogClickModal: false,
        labelWidth:150,
        column: [
          {
            label: "元数据项",
            prop: "containerName",
            rules: [{
              required: true,
              message: "请输入元数据项",
              trigger: "blur"
            }],
            cell: true,
          },
           {
            label: "编号",
            prop: "code",
            rules: [{
              required: true,
              message: "编号",
              trigger: "blur"
            }],
            cell: true,
          },
           {
            label: "数据类型",
            prop: "fieldType",
            type:'select',
            dicData:[
            // {
            //   label:'数值',
            //   value:0
            // },
            {
              label:'字符串',
              value:1
            },
            {
              label:'日期',
              value:4
            }
            ],
            rules: [{
              required: true,
              message: "数据类型",
              trigger: "blur"
            }],
            cell: true,
          },
           {
            label: "所属容器分类",
            prop: "containerType",
            type:'select',
            rules: [{
              required: true,
              message: "所属容器分类",
              trigger: "blur"
            }],
             dicData:[
            {label:'无',value:100},
            {label:'来源',value:0},
            {label:'文件联',value:1
            },{label:'内容描述',value:2},
            {label:'文件标识码',value:3}, 
            {label:'照片文件',value:4},   
            {label:'电子属性',value:5},
            {label:'数字化属性',value:6},
            {label:'电子签名',value:7},
            {label:'竣工图',value:8},
            {label:'业务层级',value:9},
            ],
     
            cell: true,
          },
            {
            label: "捕获方式",
            prop: "captureMode",
            rules: [{
              required: true,
              message: "捕获方式",
              trigger: "blur"
            }],
            type:'select',
            dicData:[{
              label:'手动',
              value:0
            },{
              label:'自动',
              value:1
            },{
              label:'手动/自动',
              value:2
            }],
            cell: true,
          },
              {
            label: "是否必选",
            prop: "mandatoryType",
            rules: [{
              required: true,
              message: "是否必选",
              trigger: "blur"
            }],
             type:'select',
             dicData:[{
              label:'可选',
              value:0
            },{
              label:'必选',
              value:1
            },{
              label:'条件选',
              value:2
            }],
            cell: true,
          }

        ]
      },
      data: [],
      setMetadataTag:false,
      MetadataformDatass:[],
    

      page2:{
        pageSize:20,
        total:0,
        current:1,
      },
      isShowedit:true,
      saveload:false,
      cancelLoad:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: false,
        addBtn: this.isShowedit,
        delBtn: this.isShowedit,
       editBtn: this.isShowedit,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {

    rowSave(row, done, loading) {
      row.fileStorageType = this.query.fileStorageType;
      metadataSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      row.fileStorageType = this.query.fileStorageType;
      metadataUpdate(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 metadataRemove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    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 = [];
      if(this.$refs.crud){
        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;
      getMetadataDetail(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        data.records.forEach((item)=>{
          item.fieldType = Number(item.fieldType)
        })
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
        // const data = [{
        //   metadataitem:'全宗名称',
        //   id:'1',
        //   datatype:'字符串',
        //   containertype:'来源',
        //   capture:'手动',
        //   isrequired:'是',
          
        // }];
        //this.page.total = 1;
        // this.data = data;
        this.loading = false;
        this.selectionClear();
    },

    setMetadata(){
      console.log(this.selectionList,'this.selectionList');
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.data.length) {
        let da = []
        this.MetadataformDatass = [...this.selectionList];
        console.log(this.MetadataformDatass,'his.formDatass111');
        // this.MetadataformDatass.forEach(val => {
        //   da.push({
        //     tableType: val.tabType,
        //     tableOwner: val.tabOwner,
        //     id: val.id,
        //     tableName: val.title,
        //     fillRate: val.fillRate,
        //   })
        // })
        // this.MetadataformDatass = da
        // console.log(this.MetadataformDatass,'this.formDatass');
        // let fa=[]
        // this.MetadataformDatass.forEach(val=>{
        //      let newarr= this.tableTypelist.filter(e => e.dictValue===val.tableType);
        //      let newarr1= this.ownerTypeList.filter(e => e.dictValue===val.tableOwner);
        //       fa.push({
        //       tableType: newarr[0].dictKey,
        //       tableOwner: newarr1[0].dictKey,
        //       id: val.id,
        //       tableName: val.tableName,
        //       fillRate: val.fillRate,
        //     })
        // })
        // this.MetadataformDatass=fa
      

      }
       this.setMetadataTag=true;
      
  
      
    },

    //新增一条数据
    toadd(){
      this.$refs.crud.rowAdd()
      //console.log(this.$refs.crud.rowCellAdd())
    },

    //切换选项
    queryChange(val){
      this.page.currentPage = 1;
      this.onLoad(this.page);
      if(val!==''){
        this.isShowedit=false
      }else{
        this.isShowedit=true
      }
      
    },

    setAllocation(){
     
      this.setMetadataTag=true;
      this.$nextTick(()=>{
        this.$refs.dialogtable.clearSelection();
      })
      this.getAllocationList();
      this.optionvalue=''
      // this.optionvalue = this.query.fileStorageType;
    },
    //为行设置独有key
  	selRowKey(row){
      // console.log(row);
      return row.id
    },
    getAllocationList(){
      getAllocationDetail(this.page2.current,this.page2.pageSize,{
        fileStorage:''
      }).then((res)=>{
        //console.log(res)
        const data = res.data.data;
        this.MetadataformDatass = data.records;
        this.page2.total = data.total;
        let checkarr=[]
        if(this.optionvalue!==''){
          checkarr=this.MetadataformDatass.filter((item)=>{
            if(item.fileStorageType.indexOf(this.optionvalue)!==-1){
              return item
            }
          })
        }
        this.$nextTick(()=>{
            checkarr.forEach((ele)=>{
               this.$refs.dialogtable.toggleRowSelection(ele,true);
            })
        })
      })
    },

    handleCurrentChange(index){
    
      this.page2.current = index;
      this.getAllocationList();
    },
    handleSizeChange(val) {
      console.log(val,'val');
      this.page2.pageSize = val;
      this.getAllocationList();
      },

    tableFormatter(row, column, cellValue){
      //console.log(row,'row');
      //console.log(column,'column');
      //console.log(cellValue,'cellValue');
      let obj = {}
      if(column.property == 'captureMode'){
        obj = {
          0:'手动',
          1:'自动',
          2:'手动/自动',
        }
        
      }else if(column.property == 'mandatoryType'){
        obj = {
          0:'可选',
          1:'必选',
          2:'条件选',
        }
      }

      return obj[cellValue];
    },

    //修改文件类型储存
    allocationSave(){
      let list = [];
      list = this.$refs.dialogtable.selection;
      //console.log(list)
      // if (list.length === 0) {
      //   this.$message.warning("请选择至少一条数据");
      //   return;
      // }

      let ids = [];
      list.forEach((item)=>{
        ids.push(item.id)
      })
      this.saveload=true
      allocation({
        ids:ids.join(','),
        type:this.optionvalue
      }).then(()=>{
        this.$message.success('操作成功');
        this.saveload=false
        this.handleCurrentChange(1);
        this.queryChange();
        this.setMetadataTag=false

      })
      
      this.optionvalue=''
    },
    //取消捕获
    cancel(row){
      this.cancelLoad=true
      cancelAllocation({
        ids:row.id,
        type:this.query.fileStorageType
      }).then(()=>{
        this.cancelLoad=false
        this.handleCurrentChange(1);
        this.queryChange();
      })
    },
    //回显选择
    changeType(val){
      this.page2.current = 1;
      this.$refs.dialogtable.clearSelection();
      this.getAllocationList()
 
    }
  }
};
</script>

<style>

</style>
