<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
    <span style="font-size: 16px;
    font-weight: 700;
">子工序列表</span>
      </div>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
      >新增子工序</el-button>
      <el-table
        v-loading="listLoading"
        :data="stepList"
        border
        fit
        stripe
        highlight-current-row
        max-height="600"
        @row-click="rowClick"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="工序步骤名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="步骤编号">
          <template slot-scope="scope">{{ scope.row.number }}</template>
        </el-table-column>
        <el-table-column label="相关设备">
          <template slot-scope="scope" v-if="scope.row.equipments">
            <el-tag v-for="item in scope.row.equipments_"
                    :key="item.number"
                    :label="item.name"
                    :value="item.number">{{item.name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="220px"
        >
          <template slot-scope="scope">
            <el-link
              v-if="checkPermission(['step_update'])"
              @click="handleEditStep(scope)"
            >编辑</el-link
            >
            <el-link
              v-if="checkPermission(['step_delete'])"
              type="danger"
              @click="handleDeleteStep(scope)"
            >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="dialogVisibles"
        :title="dialogTypes === 'edit' ? '编辑工序' : '新增工序'"
      >
        <el-form
          ref="Form"
          :model="step"
          label-width="100px"
          label-position="right"
          :rules="rule1"
        >
          <el-form-item label="工序名称" prop="name">
            <el-input v-model="step.name" placeholder="工序名称" />
          </el-form-item>
          <el-form-item label="步骤编号" prop="number">
            <el-input v-model="step.number" placeholder="工序编号" />
          </el-form-item>
          <el-form-item label="工序设备" prop="equipments">

            <el-select  style="width: 100%" multiple  v-model="step.equipments" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指导书内容" prop="instruction_content">
            <el-input  type="textarea"  :rows="3" v-model="step.instruction_content" placeholder="指导书内容" />
          </el-form-item>

          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="step.sort"
              :min="-2147483648"
              :max="2147483647"
            ></el-input-number>
          </el-form-item>

        </el-form>
        <div style="text-align: right">
          <el-button type="danger" @click="dialogVisibles = false">取消</el-button>
          <el-button type="primary" @click="confirm('Form')">确认</el-button>
        </div>
      </el-dialog>
    </el-card>
    <el-card>
      <el-row :gutter="24">
        <el-col :span="6" >
          <el-card >
            <div slot="header" class="clearfix">
          <span style="font-size: 16px;
          font-weight: 700;
          ">过程记录表</span>
            </div>
            <el-button type="primary" icon="el-icon-plus" @click="handleCreateStep"
            >新增</el-button>
            <el-table
              :data="recordformList.results"
              border
              fit
              stripe
              highlight-current-row
              height="100"
              v-el-height-adaptive-table="{bottomOffset: 50}"
              @current-change="handleCurrentChange"
            >
              <el-table-column type="index" width="50" />
              <el-table-column label="表名称">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-link
                    v-if="checkPermission(['material_update'])"
                    @click="handleEdit(scope)"
                  >编辑</el-link>
                  <el-link
                    v-if="checkPermission(['material_delete'])"
                    type="danger"
                    @click="handleDelete(scope)"
                  >删除</el-link>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog
              :visible.sync="dialogVisible"
              :title="dialogType === 'edit' ? '编辑记录表格' : '新增记录表格'"
            >
              <el-form
                ref="Forms"
                :model="recordform"
                label-width="80px"
                label-position="right"
              >

                <el-form-item label="表格名称" prop="name">
                  <el-input v-model="recordform.name" placeholder="表格名称" />
                </el-form-item>
                <el-form-item label="表格类型" prop="type">
                  <el-select  style="width: 100%" v-model="recordform.type" placeholder="请选择">
                    <el-option
                      v-for="item in typeoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>



              </el-form>
              <div style="text-align: right">
                <el-button type="danger" @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="recordformconfirm('Forms')">确认</el-button>
              </div>
            </el-dialog>
          </el-card>
        </el-col>
        <el-col :span="18" >
          <el-card >
            <div slot="header" class="clearfix">
          <span style="font-size: 16px;
          font-weight: 700;
          ">记录字段</span>
            </div>
            <el-button type="primary" icon="el-icon-plus" @click="handlefieldCreate"
            >新增</el-button>
            <el-table

              :data="fieldList.results"
              border
              fit
              stripe
              highlight-current-row
              height="100"
              v-el-height-adaptive-table="{bottomOffset: 50}"

            >

              <el-table-column type="index" width="50" />
              <el-table-column label="字段类型">
                <template slot-scope="scope">{{ options_[scope.row.field_type] }}</template>
              </el-table-column>

              <el-table-column label="字段名称">
                <template slot-scope="scope">{{ scope.row.field_name }}</template>
              </el-table-column>

              <el-table-column label="字段标识">
                <template slot-scope="scope">{{ scope.row.field_key }}</template>
              </el-table-column>
           
              <el-table-column label="选项显示名">
                <template slot-scope="scope">{{ scope.row.field_choice }}</template>
              </el-table-column>


              <el-table-column
                align="center"
                label="操作"

              >
                <template slot-scope="scope">

                  <el-link
                    v-if="checkPermission(['material_update'])"
                    @click="handlefieldEdit(scope)"
                  >编辑</el-link
                  >
                  <el-link
                    v-if="checkPermission(['material_delete'])"
                    type="danger"
                    @click="handlefieldDelete(scope)"
                  >删除</el-link
                  >
                </template>
              </el-table-column>

            </el-table>
            <el-dialog :visible.sync="dialogVisible1" :title="dialogType1 === 'edit' ? '编辑表格字段' : '新增表格字段'">
              <el-form ref="Form" :model="field" label-width="80px" label-position="right">
                <el-form-item label="字段类型" prop="field_type">
                  <el-select  style="width: 100%"  v-model="field.field_type" placeholder="请选择">
                    <el-option
                      v-for="item in fieldtypeoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="字段标识" prop="field_key">
                  <el-input v-model="field.field_key" placeholder="字段标识" onkeyup="value=value.replace(/[^A-Za-z_\/]/ig,'')"/>
                </el-form-item>
                <el-form-item label="字段名称" prop="field_name">
                  <el-input v-model="field.field_name" placeholder="字段名称" />
                </el-form-item>
                <el-form-item label="选项" v-show="field.field_type=='radio'||field.field_type=='checkbox'||field.field_type=='select'||field.field_type=='selects'">
                  <el-button @click.prevent="addDomain" style="border: none;">
                    <i class="el-icon-circle-plus-outline"></i>
                    <span style="font-size:14px;">添加</span>
                  </el-button>
                  <el-row v-for="(domain, $index) in field_choice" :key=domain+$index style="margin-bottom: 10px">
                    <el-col :span="20">
                      <el-input v-model="field_choice[$index]"  auto-complete="off"></el-input>
                    </el-col>
                    <el-col :span="3" style="text-align: center" v-if="$index!==0">
                      <i class="el-icon-remove-outline" @click.prevent="removeDomain($index,'1')" style="color: red;font-size: 16px;"></i>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <el-input-number v-model="field.sort"  :min="1" placeholder="排序"></el-input-number>
                </el-form-item>
              </el-form>
              <div style="text-align: right">
                <el-button type="danger" @click="dialogVisible1 = false">取消</el-button>
                <el-button type="primary" @click="fieldconfirm('Form')">确认</el-button>
              </div>
            </el-dialog>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
  import { getStepList, createStep,updateStep,deleteStep } from "@/api/mtm";
  import checkPermission from "@/utils/permission";
  import { getEquipmentAll } from "@/api/equipment";
  import { upUrl, upHeaders } from "@/api/file";
  import { getStep,getrecordformList,createrecordform,updaterecordform,deleterecordform,getrffieldList,createrffield,updaterffield,
    deleterffield} from "@/api/mtm";
  import vueJsonEditor from 'vue-json-editor'
  import { genTree } from "@/utils";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  const defaultstep = {
    name: "",
    number: "",
  };

  const defaultrecordform = {

  };
  const defaultfield = {

  };
  export default {
    components: { Pagination,vueJsonEditor },
    data() {
      return {
        step: defaultstep,
        stepList:[],
        upHeaders: upHeaders(),
        upUrl: upUrl(),
        fileList:[],
        listLoading: true,
        dialogVisibles: false,
        dialogTypes: "new",
        field: {
          field_type:'',
          field_key:'',
          field_name:'',
          sort:'',
          field_choice:[""],
        },
        field_choice:[''],
        options:[],
        rule1: {
          name: [{ required: true, message: "请输入", trigger: "blur" }],
          number: [{ required: true, message: "请输入", trigger: "blur" }],
        },
        recordform: defaultrecordform,
        dialogType: "new",
        dialogVisible:false,
        dialogType1: "new",
        dialogVisible1:false,
        listQueryrecordform: {
          page: 1,
          page_size: 20,
        },
        recordformList: {
          count: 0,
        },
        fieldList: {
          count: 0,
        },
        listQueryfield: {
          page: 1,
          page_size: 20,
        },
        options_: {
          'string':'文本',
          'number':'数字',
          'date': '日期',
          'datetime': '日期时间',
          'radio': '单选',
          'checkbox': '多选',
        },
        fieldtypeoptions: [{
          value: 'string',
          label: '文本'
        },
          {
            value: 'number',
            label: '数字'
          },
          {
            value: 'date',
            label: '日期'
          },
          {
            value: 'time',
            label: '时间'
          },
          {
            value: 'datetime',
            label: '日期时间'
          },
          {
            value: 'radio',
            label: '单选'
          },
          {
            value: 'checkbox',
            label: '多选'
          }
        ],
        typeoptions: [{
          value: 1,
          label: '生产记录'
        }],
      };
    },
    computed: {},
    watch: {},
    created() {
      this.step.process = this.$route.params.id;
      this.getList();
      this.getequipments()

    },
    methods: {
      //添加
      addDomain() {
        this.field_choice.push('')
      },
      //删除
      removeDomain(index){
        this.field_choice.splice(index, 1)
      },
      checkPermission,
      //子工序列表
      getList() {
        this.listLoading = true;
        getStepList(this.step.process).then((response) => {
          if (response.data) {
            this.stepList = response.data;
          }
          this.listLoading = false;
        });
      },
      //工序设备
      getequipments() {

        getEquipmentAll().then(response => {
          this.options = genTree(response.data.results);

        });
      },
      handlePreview(file) {
        if ("url" in file) {
          window.open(file.url);
        } else {
          window.open(file.response.data.path);
        }
      },
      handleUpSuccess(res, file, filelist) {
        this.step.instruction = res.data.id;
      },
      handleRemove(file, filelist){
        this.step.instruction = null;
      },




      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      resetFilter() {
        this.listQuery = {
          page: 1,
          page_size: 20,
        }
        this.getList();
      },
      handleCreateStep() {
        this.step = Object.assign({}, defaultstep);
        this.dialogTypes = "new";
        this.dialogVisibles = true;
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      rowClick(row) {

        this.stepid= row.id ;
        this.recordformLists();
      },

      handleEditStep(scope) {
        this.step = Object.assign({}, scope.row); // copy obj
        this.dialogTypes = "edit";
        this.dialogVisibles = true;

        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      handleDeleteStep(scope) {
        this.$confirm("确认删除?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(async () => {
            await deleteStep(scope.row.id);
            this.getList();
            this.$message.success("成功");
          })
          .catch((err) => {
            console.error(err);
          });
      },

      async confirm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            const isEdit = this.dialogTypes === "edit";

            if (isEdit) {
              updateStep(this.step.id, this.step).then((res) => {
                if (res.code >= 200) {
                  this.getList();
                  this.dialogVisibles = false;
                  this.$message.success("成功");
                }
              });
            } else {
              console.log(this.step)
              createStep(this.step).then((res) => {
                if (res.code >= 200) {
                  this.getList();
                  this.dialogVisibles = false;
                  this.$message.success("成功");
                }
              });
            }
          } else {
            return false;
          }
        });
      },
      handleCurrentChange(row){
        this.formID=row.id;
        this.fieldLists();

      },
      recordformLists()
      {
        this.listQueryrecordform.step=this.stepid;

        getrecordformList(this.listQueryrecordform).then((response) => {
          if (response.data) {
            this.recordformList = response.data;
          }

        });
      },
      fieldLists()
      {
        this.listQueryfield.form=this.formID
        getrffieldList(this.listQueryfield).then((response) => {
          if (response.data) {
            this.fieldList = response.data;
          }

        });
      },
      handleCreate() {
        this.recordform = Object.assign({}, defaultrecordform);
        this.dialogType = "new";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["Forms"].clearValidate();
        });
      },
      handlefieldCreate() {
        this.field = Object.assign({}, defaultfield);
        this.dialogType1 = "new";
        this.dialogVisible1 = true;
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      handleEdit(scope) {
        this.recordform = Object.assign({}, scope.row); // copy obj
        this.dialogType = "edit";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["Forms"].clearValidate();
        });
      },
      handlefieldEdit(scope) {
        this.field = Object.assign({}, scope.row); // copy obj
        this.field_choice = this.field.field_choice;
        this.dialogType1 = "edit";
        this.dialogVisible1 = true;
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      handleDelete(scope) {
        this.$confirm("确认删除?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(async () => {
            await deleterecordform(scope.row.id);
            this.recordformLists()
            this.$message.success("成功");
          })
          .catch((err) => {
            console.error(err);
          });
      },
      handlefieldDelete(scope) {
        this.$confirm("确认删除?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(async () => {
            await deleterffield(scope.row.id);
            this.fieldLists()
            this.$message.success("成功");
          })
          .catch((err) => {
            console.error(err);
          });
      },
      async recordformconfirm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            const isEdit = this.dialogType === "edit";
            if (isEdit) {
              this.recordform.step=this.stepid

              updaterecordform(this.recordform.id, this.recordform).then((res) => {
                if (res.code >= 200) {
                  this.recordformLists()
                  this.dialogVisible = false;
                  this.$message.success("成功");
                }
              });
            } else {
              this.recordform.step=this.stepid

              createrecordform(this.recordform).then((res) => {
                if (res.code >= 200) {
                  this.recordformLists()
                  this.dialogVisible = false;
                  this.$message.success("成功");
                }
              });
            }
          } else {
            return false;
          }
        });
      },
      async fieldconfirm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            const isEdit = this.dialogType1 === "edit";
            if (isEdit) {
              this.field.form=this.formID;
              this.field.field_choice = this.field_choice;
              updaterffield(this.field.id, this.field).then((res) => {
                if (res.code >= 200) {
                  this.fieldLists()
                  this.dialogVisible1 = false;
                  this.$message.success("成功");
                }
              });
            } else {
              this.field.form=this.formID;
              this.field.field_choice = this.field_choice;
              createrffield(this.field).then((res) => {
                if (res.code >= 200) {
                  this.fieldLists()
                  this.dialogVisible1 = false;
                  this.$message.success("成功");
                }
              });
            }
          } else {
            return false;
          }
        });
      },
    },
  };
</script>
<style>
  .my-label {
    background: #E1F3D8;
  }

  .my-content {
    background: #FDE2E2;
  }
</style>
