<template>
  <div>
    <Toptitle title="工序占比设置">
      <slot name="titleButton">
        <!-- <Button @click="back"
                type='primary'
                ghost
                style="margin-right:10px;">返回</Button> -->
        <Button type="primary"
                style="margin-right:10px;"
                @click="handleRowClick({},null,1)"
                ghost>新增</Button>
      </slot>
    </Toptitle>
    <div style="height:80%;overflow:auto">
    <div style="padding-top:20px">
      <Form inline :label-width='80'>
        <FormItem label="方案名称:">
          <Input style="width:150px"
                 clearable
                 v-model="search_title"
                 size="small"
                 placeholder="请输入方案名称" />
        </FormItem>
         <FormItem label="启用状态:">
           <Select v-model="search_state" style="width:150px" clearable>
             <Option value="0">
                未启用
             </Option>
             <Option value="1">
                已启用
             </Option>
           </Select>
        </FormItem>
        <FormItem>
          <Button type="primary"
                  size="small"
                  @click="init">搜索</Button>
        </FormItem>
      </Form>
    </div>
    <div style="padding:20px 0px">
      <Table border
             ref="refTableData"
             draggable
             :columns="columns"
             :data="tableData"
             @on-drag-drop="onDragDrop">
        <template slot="op"
                  slot-scope="{row,index}">
             <a @click="startUse(row)" v-show="row.state==0"
             style="margin-right:10px">启用</a>      
             <a @click="handleRowClick(row,index,4)"
             style="margin-right:10px">编辑</a>      
          <a @click="handleRowClick(row,index,2)"
             style="margin-right:10px">查看</a>
          <a @click="handleRowClick(row,index,3)" :disabled="row.state ==1">删除</a>
        </template>
      </Table>

    </div>
    </div>
    <div style="text-align:center">
          <Page :page-size-opts="[10, 20, 30, 40,100]"
                @on-page-size-change='changeSize'
                @on-change='changePage'
                :current='pageIndex'
                show-total
                :total="total"
                show-sizer
                :page-size='pageSize' />
        </div>
    <Modal class="modal"
           :title='modal_title'
           v-model='showModal'
           :mask-closable="false"
           :width="400">
    
      <div><span style="width:100px">方案名称：</span><Input style="width:80%" v-model="scheme_title"/></div>
      <span >占比设置：</span>
      <Table :data='modalData'  :columns="modalColumns" border
           :max-height='400' >
     </Table>
       <span style="margin-top:10px;display:inline-block">合计占比：<span>{{total_scale}}</span></span>
      <div class="modal-footer"
           slot="footer">
        <Button @click="showModal = false">取消</Button>
        <Button type="primary"
        v-if="modal_title !=='查看' "
                @click="handleColorConfirm">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  components: {

  },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data () {
    // 这里存放数据
    return {
      search_state:'',
      id:'',
    scheme_title:'',
    modalData:[],
   modalColumns:[
       {title:'ID',align:'center',type:'index',width:'60'},
       {title:'工序',align:'center',key:'title'},
       {title:'占比(%)',align:'center',key:'scale',render:(h,params)=>{
            const {row,index} = params;
            return h('Input',{props:{value:row.scale,disabled:this.modal_title == '查看'?true:false,type:'number'},on:{'on-change':(e)=>{
                this.modalData[index].scale = e.target.value;
                let total_scale = 0;
                this.modalData.forEach(v=>{
                   total_scale+=v.scale*1
                })
                this.total_scale = total_scale
            }}},row.scale)
       }}
   ],
      pageSize:10,
      pageIndex: 1,
      total: 0,
      total_scale:0,
        process_list:[],
        band_list:[],
        user_list:[],
        search_title:'',
        modal_title:'',
      title: '工序班组权限表',
      columns: [
        { title:'ID', type:'index', align: 'center' },
        { title: '方案名称', key: 'title', align: 'center', },
        {title:'启用状态',key:'state',align:'center',render:(h,params)=>{
          const {row} = params;
          return h('span',{},row.state == 0?'未启用':'已启用')
        }},
        { title: '操作', key: 'operation', align: 'center', slot: 'op' }
      ],
      tableData: [],
      maxSort: 0,
      showModal: false,
      //1新增2编辑
      addState: 0,
      currencyRow: {
        id:'',
        produce_ids :[],
        employee_ids:[]
      },
      currencyIndex: 0
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // this.initData()
  
    //用户列表
    // this.axios.get('/api/user').then(res=>{this.user_list = res.data.data});
    //工序列表
    this.axios.post('/api/ext_produce_list').then(res=>{this.process_list = res.data});
    // //班组列表
    // this.axios("/api/employee_list").then((res) => (this.band_list = res.data));
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {  
      this.init()
  },
  methods: {
    startUse(row){
      this.axios.post('/api/ext_produce_scale_switch',{id:row.id}).then(res=>{
        if(res.code==200){
          this.$Message.success(res.msg);
          this.init();
        }
      })
    },
      changeSize (e) {
      this.pageSize = e;
      this.init()
    },
    changePage (index) {
      this.pageIndex = index;
      
      this.init()
     
    },
    init () {
    //   this.$forceUpdate();
      this.axios.post('/api/ext_produce_scale_list', 
         {
          title: this.search_title,
          page_size:this.pageSize,
          page_index:this.pageIndex,
          state:this.search_state,
        }
      ).then(res => {
        if (res.code == 200) { 
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
      }).catch(err => {  })
    },
    back () {
      this.$router.go(-1)
    },
    handleRowClick (row, index, type) {
//1新增 2查看 3删除 4编辑
      this.currencyIndex = index
      this.addState = type
    this.id = row.id||'';
      switch (type) {
        case 1:
            this.modal_title = '新增';
            this.scheme_title = '';
         this.modalData = [];
        this.total_scale = 0;
        this.process_list.forEach(v=>{
            let obj = {};
            obj.title = v.title;
            obj.scale = '';
            this.modalData.push(obj)
        })
      this.showModal = true;
            break;
        case 2:
            this.total_scale = 0;
            this.modal_title ='查看';
           this.modalData = row.json;
           this.scheme_title = row.title;
           this.modalData.forEach(v=>{
               this.total_scale+=v.scale*1
           })
          this.showModal = true;
 
          break;
        case 3:
          this.$Modal.confirm({
            title: '确认删除？',
            content: '此操作确认后无法恢复，请确认此操作！',
            onOk: () => {
              this.axios({
                method: 'post',
                url: '/api/ext_user_permission_del',
                data: {
                  id: row.id
                }
              }).then((res) => {
                this.$Message.success(res.msg)
                this.init()
              }).catch((err) => { });
            },
            onCancel: () => { }
          })
          break;
          case 4:
              this.total_scale = 0;
            this.modal_title = '编辑';
          this.scheme_title = row.title;
          let data = JSON.parse(JSON.stringify(this.process_list));
          let title = [];
          data.forEach(v=>{
            v.scale = 0;
            title.push(v.title)
          })
         row.json.forEach(v=>{
           if(title.indexOf(v.title)>=0){
               data.forEach(m=>{
              if(m.title == v.title ){
                m.scale = v.scale;
              }
            })
           }
          
          })
           this.modalData = data;
           this.modalData.forEach(v=>{
               this.total_scale+=v.scale*1
           })
           console.log(this.modalData);
           console.log(row.json)
             this.showModal = true;
      }
    },
    handleColorChange (row, index, type) {
      this.addState = type
      this.showModal = true
    },
    handleColorConfirm () {
        if(this.total_scale!=100){
            return this.$Message.warning('合计占比必须是100%！')
        }
        console.log(this.modalData)
       let data = [];
        this.modalData.forEach(v=>{
           if(v.scale){
               data.push(v)
           }
        })
      this.axios({
        method: 'post',
        url: '/api/ext_produce_scale_edit',
        data: {
            title:this.scheme_title,
          json:{...data},
          id:this.id
        }
      }).then((res) => {
        if(res.code == 200){
        this.$Message.success(res.msg)
        this.showModal = false
        this.init()}
      }).catch((err) => { });
    },
    onDragDrop (a, b) {
      this.tableData.splice(b, 0, ...this.tableData.splice(a, 1))
      
    }
  },
  // 监听属性 类似于data概念
  computed: {
  },
  // 监控data中的数据变化
  watch: {},
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
.modal {
  div {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;

  }
}
/deep/.select_band .ivu-select-selection{
   width: 500px;
  
}
</style>