<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    class="ele-dialog-form"
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1200px"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-card
        shadow="never"
        header="基本信息"
        body-style="padding: 22px 22px 0 22px;"
      >
         <el-row>
           <el-col :span="8">
             <el-form-item
               label="产线编码:"
               prop="code"
               style="margin-bottom: 12px"
             >
               <el-input
                 clearable
                 :maxlength="20"
                 v-model="form.code"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item
               label="产线名称:"
               prop="name"
               style="margin-bottom: 12px"
             >
               <el-input
                 clearable
                 :maxlength="20"
                 v-model="form.name"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="所属工厂:" prop="extInfo.factoryId">
               <el-select
                 v-model="form.extInfo.factoryId"
                 placeholder="请选择"
                 @change="change_factoryId"
                 style="width: 100%"
               >
                 <el-option
                   v-for="item in options_factory"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id"
                 >
                 </el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="所属车间:" prop="parentId">
               <el-select
                 v-model="form.parentId"
                 placeholder="请选择"
                 style="width: 100%"
                 @change="change_workshop"
               >
                 <el-option
                   v-for="item in options.workshop"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id"
                 >
                 </el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item
               label="负责人部门:"
               prop="extInfo.principalDep"
               style="margin-bottom: 12px"
             >
               <ele-tree-select
                 clearable
                 :data="options.principalDep"
                 v-model="form.extInfo.principalDep"
                 valueKey="id"
                 labelKey="name"
                 placeholder="请选择"
                 @change="change_principalDep"
                 default-expand-all
               />
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="负责人:" prop="leaderId">
               <el-select
                 v-model="form.leaderId"
                 placeholder="请选择"
                 @change="change_principal"
                 style="width: 100%"
               >
                 <el-option
                   v-for="item in options.principal"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id"
                 >
                 </el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="联系方式:" prop="extInfo.phone">
               <el-input
                 clearable
                 :maxlength="20"
                 v-model="form.extInfo.phone"
                 οninput="value=value.replace(/[^\d]/g,'');if(value.length > 11)value = value.slice(0, 11)"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="工作节拍:" prop="extInfo.workMeter">
               <el-input
                 clearable
                 :maxlength="20"
                 v-model="form.extInfo.workMeter"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="加工能力:" prop="extInfo.workingAbility">
               <el-input
                 clearable
                 :maxlength="20"
                 v-model="form.extInfo.workingAbility"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8" style="margin-bottom: 12px">
             <el-form-item label="状态:" prop="enabled">
               <el-select
                 v-model="form.enabled"
                 placeholder="请选择"
                 style="width: 100%"
               >
                 <el-option
                   v-for="item in options.enabled"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value"
                 >
                 </el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="24" style="margin-bottom: 12px">
             <el-form-item label="地址:" prop="extInfo.location">
               <div class="location-warp">
                 <el-cascader
                   clearable
                   style="width: 400px"
                   v-model="form.extInfo.location"
                   :options="options.cityDataLabel"
                 ></el-cascader>
                 <el-input
                   class="detail"
                   clearable
                   :maxlength="20"
                   v-model="form.extInfo.locationDetail"
                   placeholder="请输入详细地址"
                 />
               </div>
             </el-form-item>
           </el-col>
           <el-col :span="24" style="margin-bottom: 12px">
             <el-form-item label="备注:" prop="remark">
               <el-input
                 clearable
                 :maxlength="100"
                 type="textarea"
                 v-model="form.remark"
                 placeholder="请输入"
               />
             </el-form-item>
           </el-col>
         </el-row>
      </el-card>
      <el-card
        shadow="never"
        header="产能计划"
        body-style="padding: 0 22px 10px 22px;"
      >
        <el-button type="primary" class="add-btn" @click="addItem">添加</el-button>
        <el-table
          :data="form.mainFactoryCapacityList"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{
            background: '#F0F3F3',
            border: 'none'
          }"
        >
          <el-table-column prop="code" label="计划周期">
            <template slot-scope="{ row }">
              <div style="width: 95%;">
                <DictSelection dictName="产能计划周期" disabled clearable v-model="row.type">
                </DictSelection>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="计划时段">
            <template slot-scope="{ row }">
              <el-date-picker
                style="width: 95%;"
                v-model="row.periodTime"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择月">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="产量目标" width="300">
             <template slot-scope="{ row }">
                <div class="row-div">
                    <el-input
                      clearable
                      :maxlength="20"
                      v-model="row.capacityTarget"
                    />
                    <DictSelection dictName="产量目标单位" clearable v-model="row.capacityUnit">
                    </DictSelection>
                </div>
             </template>
          </el-table-column>
          <el-table-column label="创建人" prop="createUserName">
          </el-table-column>
          <el-table-column label="创建时间"  prop="createTime">
             <template slot-scope="{ row }">
                {{ changeTime(row.createTime) }}
             </template>
          </el-table-column>
          <el-table-column label="状态">
             <template slot-scope="{ row }">
                <div>
                    <DictSelection dictName="产能计划状态" disabled v-model="row.status">
                    </DictSelection>
                </div>
             </template>
          </el-table-column>
          <el-table-column width="80" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="delItem(scope.$index,scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

    </el-form>
    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { saveOrUpdate, listWorkshopByParentId } from '@/api/factoryModel';
import { getUserPage } from '@/api/system/organization';
import { deepClone } from '@/components/FormGenerator/utils';
import { cityDataLabel } from 'ele-admin/packages/utils/regions';
export default {
  props: {
    options_groupId: {
      type: Array,
      default() {
        return [];
      }
    },
    options_factory: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  watch: {
    options_groupId(nval) {
      this.toTreeData(nval);
    }
  },
  data() {
    const defaultForm = {
      id: '',
      code: '',
      name: '',
      leaderId:'',
      extInfo: {
        factoryId: '',
        // principal: '', // 负责人
        principalDep: '', // 负责人部门
        phone: '', // 手机号
        workMeter: '', // 工作节拍
        workingAbility: '', // 加工能力
        locationDetail: '', // 详细地址
        location: [] // 省市区
      },
      groupId: '',
      enabled: 1,
      parentId: '',
      remark: '',
      mainFactoryCapacityList:[],
      type: 4  //  FACTORY(1, "工厂"), WORKSHOP_PLAN(2, "厂房"), WORKSHOP(3, "车间"), LINE(4, "厂线");
    };
    return {
      defaultForm,
      // 表单数据
      form: { ...defaultForm },
      // 表单验证规则
      rules: {
        code: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        'extInfo.factoryId': [
          { required: true, message: '请输入', trigger: 'change' }
        ],
        parentId: { required: true, message: '请输入', trigger: 'change' },
        'extInfo.principalDep': [
          { required: true, message: '请输入', trigger: 'change' }
        ],
        leaderId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        'extInfo.phone': [
          { min: 11, message: '手机号格式不正确', trigger: 'blur' }
        ]
      },
      visible: false,
      type: '', // add/edit
      loading: false,
      options: {
        principalDep: [],
        principal: [],
        workshop: [],
        enabled: [
          {
            label: '生效',
            value: 1
          },
          {
            label: '未生效',
            value: 0
          }
        ],
        cityDataLabel
      },
      delList:[]
    };
  },
  computed: {
    title() {
      switch (this.type) {
        case 'add':
          return '新增产线';
          break;
        case 'edit':
          return '编辑产线';
          break;
        default:
          break;
      }
    }
  },
  methods: {
    getTime(){
       const d = new Date();
       const year = d.getFullYear()
       const month = (d.getMonth() + 1).toString().padStart(2,0)
       const day = d.getDate()
       return `${year}-${month}-${day}`
    },
    addItem(){
       const time = this.getTime()
       const item = {
           type:2,
           periodTime:'',
           capacityTarget:'',
           capacityUnit:null,
           status:1,
           createUserName:this.$store.state.user.info.name,
           createTime:time
       }
       this.form.mainFactoryCapacityList.push(item)
    },
    delItem (index,row) {
      row.deleted = 1
      this.delList.push(row)
      this.form.mainFactoryCapacityList.splice(index, 1)
    },
    changeTime(str){
       var index = str.indexOf(' ')
       var time = str
       if(index>0){
          time = str.substring(0,index)
       }
       return time
    },
    open(type, row) {
     
      this.type = type;
      this.visible = true;
      if (type == 'edit') {
        for (const key of Object.keys(this.form)) {
          if (key !== 'extInfo') {
            this.form[key] = row[key];
          } else {
            for (const el of Object.keys(this.form.extInfo)) {
              this.form.extInfo[el] = row.extInfo[el];
            }
          }
        }
        // 请求下拉数据
        if (this.form.extInfo.factoryId) {
          this.getListWorkshopByParentId();
        }
        if (this.form.extInfo.principalDep) {
          this.getUserPage();
        }
      }else{
        this.form = { ...this.defaultForm };
        const info = {
          factoryId: '',
          principalDep: '', // 负责人部门
          phone: '', // 手机号
          workMeter: '', // 工作节拍
          workingAbility: '', // 加工能力
          locationDetail: '', // 详细地址
          location: [] // 省市区
        }
         this.$set(this.form,'extInfo',info)
         this.$refs.form.resetFields();
      }
    },
    /* 保存编辑 */
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;

        if (this.type == 'add') {
          delete this.form.id;
        }
        let params = deepClone(this.form)
        params.mainFactoryCapacityList = params.mainFactoryCapacityList.concat(this.delList)
        saveOrUpdate(params)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    },
    restForm() {
      this.$refs.form.clearValidate();
      this.form = { ...this.defaultForm };
    },
    handleClose() {
      this.restForm();
      this.visible = false;
      this.delList = []
    },
    // 格式化公司数据
    toTreeData(val) {
      this.options.principalDep = this.$util.toTreeData({
        data: val,
        idField: 'id',
        parentIdField: 'parentId'
      });
    },
    // 获取车间
    getListWorkshopByParentId() {
      listWorkshopByParentId(this.form.extInfo.factoryId).then((res) => {
        this.options.workshop = res;
      });
    },
    // 获取人员
    getUserPage() {
      let par = {
        groupId: this.form.extInfo.principalDep,
        size: 999
      };
      getUserPage(par).then((res) => {
        this.options.principal = res.list;
      });
    },
    // 选择工厂
    change_factoryId() {
      this.form.parentId = '';
      this.form.groupId = '';
      this.options.workshop = [];
      this.getListWorkshopByParentId();
    },
    // 选择负责人部门
    change_principalDep() {
      this.form.leaderId = '';
      this.options.principal = [];
      this.getUserPage();
    },
    // 选择车间
    change_workshop() {
      let result = this.options.workshop.find(
        (n) => n.id == this.form.parentId
      );
      this.form.groupId = result.groupId;
    },
    // 选择负责人
    change_principal() {
      let result = this.options.principal.find(
        (n) => n.id == this.form.leaderId
      );
      this.form.extInfo.phone = result.phone;
    }
  }
};
</script>
<style lang="scss" scoped>
.location-warp {
  display: flex;
  .detail {
    margin-left: 10px;
  }
}
.add-btn{
  display:black;
  margin: 20px 0;
}
.row-div{
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-input{
    margin-right:10px;
  }
}
</style>
