<template>
  <div>
    <Toptitle title="派工">
      <Button @click="goBack" type="primary" ghost style="margin-right:10px;"
        >返回</Button
      >
      <Button
        @click="handleGoPage"
        type="primary"
        ghost
        style="margin-right:10px;"
        >派工单查询</Button
      >
      <Button
        @click="handleDispatchConfirm"
        type="primary"
        style="margin-right:10px;"
        >确认派工</Button
      >
    </Toptitle>
    <div class="main">
      <Form style='display:flex;margin:15px 0;flex-wrap:wrap' :label-width='100'>
        <FormItem label='订单编号:' >
          <Select style="width:200px" v-model="searchData.order_no"  filterable @on-change='orderNoChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in orderList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='项目名称:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='图号:'>
          <Tooltip placement='right' max-width='600' transfer>
          <Select style="width:200px" v-model="searchData.url_number" multiple filterable :disabled='show' :max-tag-count='1' >
            <Option value='全部' label="全部" @click.native="total_choose"></Option>
            <Option :value="item" :label="item" v-for="(item,index) in urlNumberList" :key="index"></Option>
          </Select>
          <div slot="content">
            {{searchData.url_number.toString()}}
          </div>
          </Tooltip>
        </FormItem>
        <FormItem label='区域:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='楼栋:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='单元:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='楼层:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem label='房间号:' >
          <Select style="width:200px" v-model="searchData.residential_name"  filterable @on-change='residentialNameChange' clearable>
            <Option :value="item" :label="item" v-for="(item,index) in projectList" :key="index"></Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button  type="primary" @click="initDataSearch">搜索</Button>
        </FormItem>
      </Form>
      <div class="header">
        <Tabs v-model="currencyTag" @on-click="handleProcedureChange">
          <TabPane
            v-for="item in basicsProcedureList"
            :key="item.id"
            :label="item.title"
            :name="item.id + ''"
          />
           <div slot="extra" style="width:250px;line-height:40px;font-size:12px">
         <label style="width:130px">批量设置班组:</label>
         <Select v-model="group" size='small' style="z-index:99;position: fixed;width:150px;margin-top: 6px;margin-left:10px" @on-change='change_NK' clearable> <Option :value="_item.id" :label="_item.nickname" v-for="_item in groupList" :key="_item.id">
         </Option> </Select>
        </div>
        </Tabs>
       
      </div>
      <div class="content">
        <Table
          :columns="tableColumns"
          border
          max-height="700"
          @on-selection-change="handleSelectionChange"
          :data="tableData"
          ref="y_table"
           :loading='loading'
        >
          <template slot="slotGroup" slot-scope="{ row, index }">
            <Select
              v-model="row.employee_id"
              size="small"
              @on-change="
                (e) =>
                  handleGroupSelect(
                    e,
                    tableData[index],
                    index,
                    tableData[index].employee_id
                  )
              "
              clearable
              style="width: 150px"
            >
              <Option
                v-for="sitem in row.employee_list"
                :key="sitem.id"
                :label="sitem.nickname"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </template>
          <template slot="slotSet" slot-scope="{ row, index }">
            <a style="margin:0 5px" @click="handleSet(row, index)">详情</a>
            <!-- <a style="margin:0 5px" @click="handleDispatchConfirm(row, index)"
              >派工</a
            > -->
          </template>
        </Table>
       
      </div>
    </div>
     <div class="pageSlotStyle">
          <Page :page-size-opts="[10, 20, 30, 40,100,1000]"
                @on-page-size-change='changeSize'
                @on-change='changePage'
                :current='page_index'
                show-total
                :total="total"
                show-sizer
                :page-size='page_size' />
        </div>
    <Modal v-model="showModal" title="确认派工">
      <Form :label-width="85" ref="forms" :model="dispatchInfo">
        <FormItem label="选择时间">
          <DatePicker
            :options="options"
            style="width:100%;"
            v-model="dispatchTime"
            clearable
            type="daterange"
            split-panels
            placeholder="请选择日期"
          ></DatePicker>
        </FormItem>

        <FormItem label="点工单形式">
          <RadioGroup v-model="dispatchInfo.work_type">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="日薪" v-if="dispatchInfo.work_type == 1">
          <Input v-model="dispatchInfo.user_salary">
            <span slot="append">元</span>
          </Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="showModal = false">取消</Button>
        <Button type="primary" @click="handleDispatch(subArr, subUrl)"
          >确认</Button
        >
      </div>
    </Modal>
    <Modal v-model="showModalAll" title="全部派工">
      <Table
        :columns="modalTableColumns"
        border
        max-height="700"
        :data="modalTableData"
      >
        <template slot="slotGroup" slot-scope="{ row, index }">
          <Select
            v-model="row.employee_id"
            size="small"
            @on-change="
              (e) =>
                handleGroupSelect(
                  e,
                  modalTableData[index],
                  index,
                  modalTableData[index].employee_id
                )
            "
            clearable
            style="width: 120px"
          >
            <Option
              v-for="sitem in row.employee_list"
              :key="sitem.id"
              :label="sitem.nickname"
              :value="sitem.id"
            >
            </Option>
          </Select>
        </template>
      </Table>
      <div slot="footer">
        <Button @click="showModalAll = false">取消</Button>
        <Button type="primary" @click="handleDispatchAllConfirm">确认</Button>
      </div>
    </Modal>
  </div>
</template>

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

export default {
  name: "",
  components: {},
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      loading:false,
      show:true,
      orderList:[],
      urlNumberList:[],
      projectList:[],
      tableColumns: [
        { title: '全选', type: 'selection', align: 'center', minWidth: 60 },
        { title: "工序", align: "center", key: "title", minWidth: 150 },
        { title: "图号", align: "center", key: "url_number", minWidth: 150 ,ellipsis:'true',tooltip:'true' },
        { title: "部件总数", align: "center", key: "num", minWidth: 150 },
        {
          title: "班组",
          align: "center",
          key: "",
          minWidth: 200,
          slot: "slotGroup",
        },
         { title: "区域", align: "center", key: "num", minWidth: 150 },
          { title: "楼栋", align: "center", key: "num", minWidth: 150 },
           { title: "单元", align: "center", key: "num", minWidth: 150 },
            { title: "楼层", align: "center", key: "num", minWidth: 150 },
             { title: "房间号", align: "center", key: "num", minWidth: 150 },
        {
          title: "操作",
          align: "center",
          key: "",
          minWidth: 100,
          slot: "slotSet",
        },
      ],
      modalTableColumns: [
        { title: "工序", align: "center", key: "title", minWidth: 150 },
        { title: "部件总数", align: "center", key: "num", minWidth: 150 },
        {
          title: "班组",
          align: "center",
          key: "",
          minWidth: 150,
          slot: "slotGroup",
        },
      ],
      modalTableData: [{}],
      tableData: [{}],
      page_index: 1,
      page_size: 10,
      total: 0,
      group:'',
      basicsProcedureList: [],
      groupList: [],
      currencyTag: "1",
      dispatchTime: [],
      wood_select:[],
      wood_group:'',
      paint_select:[],
      paint_group:'',
      packing_select:[],
      packing_group:'',
      transit_select:[],
      transit_group:'',
      install_select:[],
      install_group:'',
      selected: [],
      searchData:{
        order_no:'',
        url_number:[],
        residential_name:''
      },
      showModal: false,
      showModalAll: false,
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      dispatchInfo: {},
      subArr: [],
      subUrl: "",
      show_type:true,
      url_number_type:true,
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 获取工序分类列表
    this.axios({ method: "get", url: "/api/basics_procedure_index" })
      .then((res) => {
        (this.basicsProcedureList = res.data.data),
          (this.currencyTag =
            localStorage.getItem("dispatchTag") || this.currencyTag + "");
      })
      .catch((err) => {});
    //获取班组列表
    this.axios("/api/employee_list").then(
      (res) => (this.groupList = res.data.data)
    );
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initData();
     this.axios({
        method: "post",
        url: "/api/order_produce_list",
        data: {
          basics_procedure_id:
            localStorage.getItem("dispatchTag") || this.currencyTag,
            page_index:this.page_index,
            page_size:this.page_size,
        },
      }).then(res=>{
        this.orderList = res.data.order_no;
        this.projectList = res.data.residential_name;
      })
  },
  methods: {
    total_choose(){
      console.log(this.urlNumberList)
        if(this.searchData.url_number.indexOf('全部')>=0){
                 
               this.searchData.url_number = JSON.parse(JSON.stringify(this.urlNumberList))
              this.searchData.url_number.unshift('全部')
         
        }else{
          this.searchData.url_number = [];
        }
       
    },
  initDataSearch(){
    if(this.searchData.residential_name&&this.searchData.order_no){
      this.url_number_type = false;
      this.initData();
    }else{
      this.url_number_type = true;
      this.initData();
    }
  },
  async residentialNameChange(val){
       await this.axios.get('/api/order_produce_order_no',{params:{residential_name:val}}).then(res=>{
            this.searchData.order_no = res.data.order_no
           })
           if(this.searchData.residential_name&&this.searchData.order_no){

              this.show = false;
              this.axios.get('/api/order_produce_url_number',{params:{...this.searchData,type_id:this.currencyTag}}).then(res=>{
                this.urlNumberList = res.data;
                this.searchData.url_number = [];
                   this.wood_select=[]
                 this.paint_select=[]
     this.packing_select=[]
      this.transit_select=[]
   this.install_select=[]
              })
           }else{
             this.show = true;
             if(this.show){
               this.searchData.url_number = []
             }
           }
         
    },
 async orderNoChange(val){
           await this.axios.get('/api/order_produce_order_no',{params:{order_no:val}}).then(res=>{
            this.searchData.residential_name = res.data.residential_name
           })
           if(this.searchData.residential_name&&this.searchData.order_no){
              this.show = false;
              this.axios.get('/api/order_produce_url_number',{params:{...this.searchData,type_id:this.currencyTag}}).then(res=>{
                this.urlNumberList = res.data;
                this.searchData.url_number = [];
                this.wood_select=[]
                 this.paint_select=[]
     this.packing_select=[]
      this.transit_select=[]
   this.install_select=[]
              })
           }else{
             this.show =true;
              if(this.show){
              this.searchData.url_number = [];
             }
           }
    },
    change_NK(row){
      if(row == null){
        return
      }else{
      if(this.currencyTag == 1){
        if(this.wood_select.length == 0){
          this.$Message.warning('请先选择工序！');
          setTimeout(()=>{
            this.group = '';
          })
        }else{
        this.tableData.forEach(item=>{
          this.wood_select.forEach(_item=>{
            if(_item.id == item.id){
              item.employee_id = row;
              item._checked = true;
              _item.employee_id = row;
            }
          })
        })
        }
      }
      if(this.currencyTag == 2){
        if(this.paint_select.length == 0){
          this.$Message.warning('请先选择工序！');
       setTimeout(()=>{
            this.group = '';
          })
        }else{
        this.tableData.forEach(item=>{
          this.paint_select.forEach(_item=>{
            if(_item.id == item.id){
              item.employee_id = row;
              item._checked = true;
              _item.employee_id = row;
            }
          })
        })
        }
      }
       if(this.currencyTag == 3){
        if(this.packing_select.length == 0){
          this.$Message.warning('请先选择工序！');
         setTimeout(()=>{
            this.group = '';
          })
        }else{
        this.tableData.forEach(item=>{
          this.packing_select.forEach(_item=>{
            if(_item.id == item.id){
              item.employee_id = row;
              item._checked = true;
              _item.employee_id = row;
            }
          })
        })
        }
      }
       if(this.currencyTag == 4){
        if(this.transit_select.length == 0){
          this.$Message.warning('请先选择工序！');
       setTimeout(()=>{
            this.group = '';
          })
        }else{
        this.tableData.forEach(item=>{
          this.transit_select.forEach(_item=>{
            if(_item.id == item.id){
              item.employee_id = row;
              item._checked = true;
              _item.employee_id = row;
            }
          })
        })
        }
      }
       if(this.currencyTag == 5){
        if(this.install_select.length == 0){
          this.$Message.warning('请先选择工序！');
         setTimeout(()=>{
            this.group = '';
          })
        }else{
        this.tableData.forEach(item=>{
          this.install_select.forEach(_item=>{
            if(_item.id == item.id){
              item.employee_id = row;
              item._checked = true;
              _item.employee_id = row;
            }
          })
        })
        }
      }
      }
    },
    initData() {
      this.axios({
        method: "post",
        url: "/api/order_produce_list",
        data:{
          basics_procedure_id:
            localStorage.getItem("dispatchTag") || this.currencyTag,
            page_index:this.page_index,
            page_size:this.page_size,
            ...this.searchData
        },
      })
        .then((res) => {
          this.group = '';
          this.total = res.data.total;
          this.tableData = res.data.data;
          this.tableData.forEach((element) => {
            if(this.url_number_type){
              element.url_number = '';
            }
            element.produce_id = element.id;
            element.employee_id ? "" : (element.employee_id = "");
            if(this.currencyTag == 1  ){
                this.wood_select.forEach(_item=>{
                  if(_item.id == element.id){
                     element._checked = true;
                     element.employee_id = _item.employee_id;
                  }
                })
            }


             if(this.currencyTag == 2 ){
                this.paint_select.forEach(_item=>{
                  if(_item.id == element.id){
                     element._checked = true;
                     element.employee_id = _item.employee_id;
                  }
                })
            }



             if(this.currencyTag == 3 ){
                this.packing_select.forEach(_item=>{
                  if(_item.id == element.id){
                     element._checked = true;
                     element.employee_id = _item.employee_id;
                  }
                })
            }



              if(this.currencyTag == 4 ){
                this.transit_select.forEach(_item=>{
                  if(_item.id == element.id){
                     element._checked = true;
                     element.employee_id = _item.employee_id;
                  }
                })
            }



            if(this.currencyTag == 5 ){
                this.install_select.forEach(_item=>{
                  if(_item.id == element.id){
                     element._checked = true;
                     element.employee_id = _item.employee_id;
                  }
                })
            }
          });
          this.$forceUpdate();
          this.loading = false;
        })
        .catch((err) => {});
    },
    goBack() {
      this.$router.go(-1);
    },
    handleGoPage() {
      this.$router.push({ path: "/cms/Dispatching/DispatchedList" });
    },
    handleSet(row, index) {
      this.$router.push({
        path: "/cms/Dispatching/DispatchingDetail",
        query: {
          produce_id: row.id,
        },
      });
    },
    // handleDispatchConfirm(row, index) {
    //   if (row.employee_id) {
    //     this.selected = [row];
    //     this.showModal = true;
    //     this.subArr = JSON.parse(JSON.stringify(this.selected));
    //     this.subUrl = "/api/order_produce_pull_all";
    //   } else {
    //     this.$Message.warning("请选择班组");
    //   }
    // },

  handleDispatchConfirm() {
    if (this.wood_select.length!=0||this.paint_select.length!=0||this.packing_select.length!=0||this.transit_select.length!=0||this.install_select.length!=0) {
      this.show_type = true;
        this.subArr =[...this.wood_select,...this.paint_select,...this.packing_select,...this.transit_select,...this.install_select];
        console.log(this.subArr);
        this.subUrl = "/api/order_produce_pull_all";
       try{this.subArr.forEach(v=>{
          if(!v.employee_id){
            this.show_type = false;
            throw new Error();
          }
        })} catch(e){
          
          this.$Message.warning('请设置班组');
        };
        this.showModal = this.show_type;
      } else {
        this.$Message.warning("请选择工序");
      }
    },
    handleDispatch(target, url) {
      if (!this.dispatchTime[0]) {
        this.$Message.warning("请选择时间");
      } else {
        this.dispatchInfo.start_time = new Date(this.dispatchTime[0])
          .toLocaleDateString()
          .replace(/\//g, "-");
        this.dispatchInfo.end_time = new Date(this.dispatchTime[1])
          .toLocaleDateString()
          .replace(/\//g, "-");
        target.forEach((element) => {
          element.start_time = this.dispatchInfo.start_time;
          element.end_time = this.dispatchInfo.end_time;
          element.work_type = this.dispatchInfo.work_type;
          element.user_salary = this.dispatchInfo.user_salary || "";
          // element.order_no = this.searchData.order_no;
          // element.url_number = this.searchData.url_number;
          // element.residential_name = this.searchData.residential_name;
        });
        console.log(target);
        this.axios({
          method: "post",
          url,
          data: {
            ...target,
            ...this.searchData
          },
        })
          .then((res) => {
            if (res.code == 200) {
              this.showModal = false;
              this.$Message.success(res.msg || "操作成功");
              this.initData();
              this.dispatchInfo = {};
              this.dispatchTime = [];
            }
          })
          .catch((err) => {});
      }
    },
    handleDispatchAllConfirm() {
      let flag = true;
      this.modalTableData.forEach((element) => {
        if (!element.employee_id || element.employee_id <= 0) {
          flag = false;
        }
      });
      if (flag) {
        (this.showModalAll = false), (this.showModal = true);
        this.subArr = JSON.parse(JSON.stringify(this.modalTableData));
        this.subUrl = "/api/all_order_produce_pull";
      } else {
        this.$Message.warning("请选择班组");
      }
    },
    handleDispatchAllOpen() {
      this.axios
        .get("/api/get_all_order_produce", {
          params: {
            basics_procedure_id:
              localStorage.getItem("dispatchTag") | this.currencyTag,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.modalTableData = res.data;
            this.modalTableData.forEach((element) => {
              element.produce_id = element.id;
            });
            this.showModalAll = true;
          }
        });
    },
    changePage(e) {
      this.page_index = e;
      this.initData();
    },
    changeSize(e) {
      this.page_size = e;
      this.initData();
    },
    handleProcedureChange(val) {
      this.loading = true;
      this.selected = [];
      this.currencyTag = val;

      localStorage.setItem("dispatchTag", val);
       this.axios.get('/api/order_produce_url_number',{params:{...this.searchData,type_id:this.currencyTag}}).then(res=>{
                this.urlNumberList = res.data;
                });
        this.searchData.url_number =[];         
      this.initData();  
      this.page_index = 1;
      this.page_size = 10;
    },
    handleSelectionChange(selection) {
    try{
        if(this.currencyTag == 1){
       this.wood_select = selection;
       this.wood_select.forEach((item,index)=>{
                if(this.wood_select[index].id!=this.tableData[index].id){
                this.$Message.error('请按流程选择工序!');
                throw new Error();
          }
       })
      }
      if(this.currencyTag == 2){
        this.paint_select =selection;
       this.paint_select.forEach((item,index)=>{
                if(this.paint_select[index].id!=this.tableData[index].id){
                this.$Message.error('请按流程选择工序!');
                throw new Error();
          }
       })
      }
      if(this.currencyTag == 3){
        this.packing_select =selection;
       this.packing_select.forEach((item,index)=>{
                if(this.packing_select[index].id!=this.tableData[index].id){
                this.$Message.error('请按流程选择工序!');
                throw new Error();
          }
       })
      }
      if(this.currencyTag == 4){
        this.transit_select = selection;
       this.transit_select.forEach((item,index)=>{
                if(this.transit_select[index].id!=this.tableData[index].id){
                this.$Message.error('请按流程选择工序!');
                throw new Error();
          }
       })
      }
      if(this.currencyTag == 5){
        this.install_select = selection;
       this.install_select.forEach((item,index)=>{
                if(this.install_select[index].id!=this.tableData[index].id){
                this.$Message.error('请按流程选择工序!');
                throw new Error();
          }
       })
      }
    }catch(e){
           
    }
    },
    handleGroupSelect(e, row, index, value) {
      // if (this.selected.length > 0) {
      //   this.selected.forEach(element => {
      //     if (element.id == row.id) {
      //       element.employee_id = value
      //     }
      //   });
      // }
      row.employee_id = e;
      if(this.currencyTag == 1){
        this.tableData.forEach(item=>{
            this.wood_select.forEach(_item=>{
              if(item.id == _item.id){
                item._checked = true;
                _item.employee_id = item.employee_id;
              }
            })
        }) 
      }
      if(this.currencyTag == 2){
        this.tableData.forEach(item=>{
            this.paint_select.forEach(_item=>{
              if(item.id == _item.id){
                item._checked = true;
                _item.employee_id = item.employee_id;
              }
            })
        }) 
      }
       if(this.currencyTag == 3){
        this.tableData.forEach(item=>{
            this.packing_select.forEach(_item=>{
              if(item.id == _item.id){
                item._checked = true;
                _item.employee_id = item.employee_id;
              }
            })
        }) 
      }
       if(this.currencyTag == 4){
        this.tableData.forEach(item=>{
            this.transit_select.forEach(_item=>{
              if(item.id == _item.id){
                item._checked = true;
                _item.employee_id = item.employee_id;
              }
            })
        }) 
      }
       if(this.currencyTag == 5){
        this.tableData.forEach(item=>{
            this.install_select.forEach(_item=>{
              if(item.id == _item.id){
                item._checked = true;
                _item.employee_id = item.employee_id;
              }
            })
        }) 
      }
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.pageSlotStyle {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
}
.main{
  height:600px;

}
</style>
